Angular input directive
http://angularjs.org/
by anup1986
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div id="container" ng-controller="MyCtrl">
<div class="row">
<form class="form-inline col-sm-3">
<div editonclick="{{text}}" ng-model="text"></div>
<div editonclick="{{text2}}" ng-model="text2"></div>
</form>
</div>
</div>
CSS
div#container {
margin: 20px;
}
div[editonclick] {
margin: 20px 0 0 0;
}
p {
margin-top: 20px;
}
JavaScript
var app = angular.module('myApp', []);
app.directive('onEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.onEnter);
});
event.preventDefault();
}
});
};
});
app.directive('onEsc', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 27) {
scope.$apply(function () {
scope.$eval(attrs.onEsc);
});
event.preventDefault();
}
});
};
});
app.directive('editonclick', function ($timeout) {
return {
restrict: 'A',
scope: {
value: '=ngModel'
},
template: '<p ng-show="!editing" ng-click="toggleEdit()">{{value}}</p>' +
'<div class="input-group" ng-show="editing">' +
'<input class="form-control" on-esc="cancel()" on-enter="save()" ng-model="value" type="text" autofocus="autofocus"/>' +
'<span class="input-group-btn">' +
'<button class="btn btn-primary" type="button" ng-click="save()">Save</button>' +
'<button class="btn btn-danger" type="button" ng-click="cancel()">Cancel</button>' +
'</span>' +
'</div>',
link: function (scope, el, attrs) {
var oldValue;
scope.$watch("value", function (newVal, old) {
if (typeof (oldValue) === "undefined" && typeof (newVal) !== "undfined") oldValue = newVal;
console.clear();
console.log('new:', newVal, ', old:', old, ', oldvalue:', newVal);
});
scope.editing = false;
scope.save = function () {
oldValue = scope.value;
...