javascript - Reinvoke function on model update in AngularJS -
first off, apologize in advance if terminology or approach off - come structural engineering background , trying learn javascript , angularjs through small pet project.
my question is: how re-invoke function updateme()
within service whenever model updates. sample code , plunker below.
initially, code run fine , result calculated. if a
or b
updated, updated values propagated controllers, value of result
not updated.
i've tried playing around $scope.$watch()
couldn't work, nor sure right approach.
in actual project, function in question depends on several properties of myservice object, , generates json data plotted n3-charts. want make plot interactive regenerating data when user updates property of myservice object.
angular .module('app', []); //some function evaluated when data in myservice changes function updateme(x, y) { return x * y; } //define service (to provide data multiple ctrls) function myservice() { var myservice = this; myservice.a = 2; myservice.b = 5; // trying 'result' update when of input parameters update myservice.result= updateme(myservice.a, myservice.b); } angular .module('app') .service('myservice', myservice); // controller uses myservice data in view function firstctrl(myservice) { var vm = this; vm.myservice = myservice; } angular .module('app') .controller('firstctrl', firstctrl); // controller uses myservice data in view function secondctrl(myservice) { var vm = this; vm.myservice = myservice; } angular .module('app') .controller('secondctrl', secondctrl);
here's plunker similar code above.
you can use ng-change function recalculate values
<input type="number" step="1" ng-model="first.myservice.a" ng-change="first.myservice.updateall(first.myservice.a)"> myservice.updateall=function() { myservice.result = updateme(myservice.a, myservice.b); }
whenever there change on model updateall
triggers , can recalculations inside that.
here working example.
Comments
Post a Comment