简体   繁体   中英

AngularJS directive $watch two-way binding

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

In other words: I don't want to $watch to fire on the value if the change was internal (ie the scope variable was changed in the controller or in the link function).

Here 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 who can I distinguish?

There's no option to distinguish between these two events, so you'll have to implement that behaviour yourself.

I would do it by setting a flag whenever you make a change "internally", then checking for it in the watch.

For example:

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 fiddle .

Your alternative (more complex) approach, is creating a custom directive that uses the ngModel API. That distinguishes between DOM -> Model (external) and Model -> DOM (internal) changes. I don't think it's necessary here, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM