AngularJS: Inline edit
by cambiata
HTML
<script src="http://ci.angularjs.org/job/angular.js-angular-master/229/artifact/build/pkg/0.10.7-e86bafec/angular-0.10.7-e86bafec.js"></script>
<!-- inlined template for the component -->
<script type="text/ng-template" id="componentTpl.html">
<span ng-hide="editMode" ng-click="editMode=true;value=model()">{{model()}}</span>
<input type="text" ng-model="value" ng-show="editMode" ng-model-instant ng-enter="editMode=false" ng-change="model(value)"/>
</script>
<div ng-controller="Controller">
<div ng-repeat="i in items">
{{i.id}}: <inline-edit model="i.name"></inline-edit>
</div>
</div>
CSS
span {
cursor: pointer;
}
JavaScript
var app = angular.module('zdam', []);
app.directive('ngEnter', function() {
return function(scope, elm, attrs) {
elm.bind('keypress', function(e) {
if (e.charCode === 13) scope.$apply(attrs.ngEnter);
});
};
});
app.directive('inlineEdit', function() {
return {
// can be in-lined or async loaded by xhr
// or inlined as JS string (using template property)
templateUrl: 'componentTpl.html',
scope: {
model: 'accessor'
}
};
});
function Controller($scope) {
$scope.items = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
}