问题描述
我想内部变革和双向数据绑定属性的外部变化来区分(=
)。
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 (i.e. the scope variable was changed in the controller or in the link function).
下面一些code,说明我的问题:
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);
}
}
})
现场演示:
任何想法我谁可以区分?
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.
例如:
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之间的区分。我不认为有必要在这里,虽然。
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.
这篇关于AngularJS指令$腕表双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!