我试图通过双向数据绑定属性(‘=’)来区分内部更改和外部更改.
换句话说:如果更改是内部的(即在控制器或链接函数中更改了范围变量),我不希望$watch触发该值.
这里有一些代码说明了我的问题:
<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); } } })
现场演示:
http://jsfiddle.net/B7hT5/11/
任何想法我能分辨谁?
解决方法
没有选择区分这两个事件,所以你必须自己实现这个行为.
我会在你“内部”进行更改时设置一个标志,然后在手表中检查它.
例如:
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); }
您的替代(更复杂)方法是创建使用ngModel API的自定义指令.区分DOM – >模型(外部)和模型 – > DOM(内部)更改.不过,我认为这不是必要的.