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.

  1. first it's not declarative , have search code mytestproperty find binding.
  2. 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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -