AngularJS: Inline edit

by yahyaKACEM

HTML

<!--  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 {
        restrict: 'E',
        // can be in-lined or async loaded by xhr
        // or inlined as JS string (using template property)
        templateUrl: 'componentTpl.html',
        scope: {
            model: '=' 
        }
    };
});

function Controller($scope, $timeout) {
    $scope.items = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
}