angular.module('MyApp') .directive('edit', function ($parse) { var directive = {} directive.scope = true directive.link = function (scope, element, attrs) { var callback = function (item) {} var model = $parse(attrs.edit) var editor = scope.editor = {} if (attrs.callback != null) callback = $parse(attrs.callback)(scope) editor.save = function () { var data = model(scope) callback(scope.item) if (scope.item._key !== editor.key) delete data[editor.key]; data[scope.item._key] = scope.item delete scope.item._key editor.revert() } editor.revert = function () { editor.key = null scope.item = {} } scope.$watch('editor.key', function (value) { if (value == null) { editor.revert() } else { var data = model(scope) scope.item = angular.copy(data[value] || {}) scope.item._key = value } }) editor.revert() } return directive })