AngularJS directive $ watch two-way binding

I am trying to distinguish between an internal change and an external change with a two-way data-bound attribute ( '=' ).

In other words: I do not want $watch run the value if the change was internal (i.e. the region variable was changed in the controller or in the communication function).

Here is some code that illustrates my problem:

HTML

  <div ng-app="myApp"> <div ng-controller="MainCtrl"> <input ng-model="value"/> <mydemo value="value"></mydemo> </div> </div> 

Javascript

 app.directive('mydemo', function () { return { restrict: 'E', scope: { value: "=" }, template: "<div id='mydiv'>Click to change value attribute</div> Value:{{value}}", link: function (scope, elm) { scope.$watch('value', function (newVal) { //Don't listen if the change came from changeValue function //Listen if the change came from input element }); // Otherwise keep any model syncing here. var changeValue = function() { scope.$apply(function () { scope.value = " from changeValue function"; }); } elm.bind('click', changeValue); } } }) 

Live demo: http://jsfiddle.net/B7hT5/11/

Any idea I can tell?

+5
source share
1 answer

There is no way to distinguish between these two events, so you have to implement this behavior yourself.

I would do this by setting the flag when you make the change β€œinternally” and then check it in the watch.

For instance:

 link: function (scope, elm){ var internal = false; scope.$watch('value', function (newVal) { if(internal) return internal = false; // Whatever code you want to run on external change goes here. console.log(newVal); }); var changeValue = function(){ scope.$apply(function (){ internal = true; // flag internal changes scope.value = " from changeValue function"; }); } elm.bind('click', changeValue); } 

See the updated script .

Your alternative (more complex) approach creates a custom directive that uses the ngModel API. This distinguishes between DOM β†’ Model (external) and Model β†’ DOM (internal) changes. I do not think this is necessary here.

+7
source

Source: https://habr.com/ru/post/1201346/


All Articles