AngularJS editable directive
HTML
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="miniapp" ng-controller="Ctrl">
<p>Hello, my friend <editable model="yourname">{{yourname}}</editable>, this is an example of <editable model="yourframework">AngularJS</editable></p>
<p> </p>
<p>(click on any underline text to edit it. Hit enter to exit)</p>
<div>
{{yourname}}
</div>
</div>
JavaScript
var $scope;
var app = angular.module('miniapp', []);
app.directive('editable', function() {
return {
restrict: 'E',
scope: {model: '='},
replace: false,
template:
'<span>'+
'<input type="text" ng-model="model" ng-show="edit" ng-enter="edit=false"></input>'+
'<span ng-show="!edit" style="text-decoration:underline">{{model}}</span>'+
'</span>',
link: function(scope, element, attrs) {
scope.edit = false;
element.bind('click', function() {
scope.$apply(scope.edit = true);
element.find('input').focus();
});
}
};
});
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind('keypress', function(e) {
if (e.charCode === 13 || e.keyCode ===13 ) {
scope.$apply(attrs.ngEnter);
}
});
};
});
function Ctrl($scope) {
$scope.yourname = "Shakespeare";
$scope.yourframework = "AngularJS";
}