angularjs - Undo in Angular Directive -


i've built directive has object passed via bindtocontroller, intent of editing it. edit working great until needed cancel edit. undo, needed create shadow copy of original object, edit it, copy or discard based on save or cancel. i've tried achieve in link property of directive, using scope.watch on the controller property. watch fires once, when initialized, property undefined because nothing has used yet, expected. never fires again though, once real object put property.

where have gone wrong? should got using $scope because i'm having issues getting reference controller? why watch firing once?

the directive:

angular.module("isg").directive('isgeditingfunddirective', function () {     var ctrl = null;     var isgeditingfunddirectivecontroller = function () {         ctrl = this; // getting reference controller can used in link function.  there better way this?          this.cancel = function () {             // undo edit             ctrl.fund = null;         };          this.save = function () {             // save original model             angular.copy(ctrl.shadow, ctrl.fund);              // set null because aren't editing anymore             ctrl.fund = null;         }     }      var isgeditingfunddirectivelink = function (scope, element, attrs) {         // need link can undo edit             scope.$watch(ctrl.fund, function (orig, updated) {             // trying watch fund property in controller can create copy undo later.                // never fires real value             angular.copy(ctrl.fund, ctrl.shadow);         });     }      return {         restrict: "e",         controlleras: 'editfundctrl',         templateurl: "/angular/editfund",         bindtocontroller: {             fund: "=fund"         },         controller: isgeditingfunddirectivecontroller,         link: isgeditingfunddirectivelink      }; }); 

the template:

editing fund  name: <input ng-model="editfundctrl.shadow.fundname"/> <button ng-click="editfundctrl.cancel()">cancel</button> <button ng-click="editfundctrl.save()">save</button>  <pre>{{editfundctrl.fund}}</pre> 

basically trying put watch on variable belongs this context of controller. $watch function accepts string scope variable name or function evaluate on each digest cycle.

you solve issue having putting function inside watcher.

scope.$watch(function(){     return ctrl.fund; }, function (orig, updated) {    // trying watch fund property in controller can create copy undo later.       // never fires real value         angular.copy(ctrl.fund, ctrl.shadow); }); 

otherwise solve problem having angular.bind on this, refer this answer


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -