javascript - Is there a way in Angular to react on model changes without using $watch? -
i'm implementing simple spinner control in angularjs , want react both on user input , changes +/- buttons. here html:
<input type='button' ng-click="myproperty = myproperty - 1" value="-"> <input type='text' ng-model="myproperty" ng-change="log('changed ngchange')"> <input type='button' ng-click="myproperty = myproperty + 1" value="+">
but track 'user-changes' far ngchange
supports user-interaction updates per documentaiton
so i'm looking @ $scope.$watch
frederik recommends:
$scope.$watch('myproperty', function() { $scope.log('changed $watch'); });
see plunker demo
but doesn't seem right enogh.
- first it's not declarative , have search code
mytestproperty
find binding. - if want place
$scope.log
in separate model have either inject$scope
or binding in controller. , far understand both ways not considered best practicies.
some people think $watch
bad thing in general number of other reasons. solution advised there (which calling log
in ngclick directly) doesn't make diference me. basicly have manually track changes , if new actor comes have copy logic there.
so the questions be: there way allows automaticly keep track of model updates without $watch? , how bad idea implement own derective if there such way?
there couple of ways this, elegant way requiring ngmodel of input , use view / manipulate value.
here your updated plunker.
.directive('outputit', function() { return { restrict: 'a', scope: { outputit: '&' }, require: '?ngmodel', link: function(scope, element, attrs, ngmodelctrl) { ngmodelctrl.$parsers.push(function(val) { //console.log("the model changed input") scope.outputit()(val); }); ngmodelctrl.$formatters.push(function(viewvalue) { //console.log("the model changed outside."); scope.outputit()(viewvalue); return viewvalue; }); } } })
to find out more it, here cool article it: atricle
good luck!
Comments
Post a Comment