如何为自定义指令实现 ng-change
我有一个带有类似模板的指令
I have a directive with a template like
<div>
<div ng-repeat="item in items" ng-click="updateModel(item)">
<div>
My directive is declared as:
我的指令声明为:
I would like to have ng-change
called when an item is clicked and the value of foo
has been changed already.
我希望在单击项目并且 foo
的值已经更改时调用 ng-change
.
That is, if my directive is implemented as:
也就是说,如果我的指令实现为:
<my-directive items=items ng-model="foo" ng-change="bar(foo)"></my-directive>
I would expect to call bar
when the value of foo
has been updated.
我希望在 foo
的值更新后调用 bar
.
With code given above, ngChange
is successfully called, but it is called with the old value of foo
instead of the new updated value.
使用上面给出的代码,ngChange
被成功调用,但它是用 foo
的旧值而不是新的更新值调用的.
One way to solve the problem is to call ngChange
inside a timeout to execute it at some point in the future, when the value of foo
has been already changed. But this solution make me loose control over the order in which things are supposed to be executed and I assume that there should be a more elegant solution.
解决问题的一种方法是在超时内调用 ngChange
以在将来的某个时间执行它,当 foo
的值已经更改时.但是这个解决方案让我无法控制事情的执行顺序,我认为应该有一个更优雅的解决方案.
I could also use a watcher over foo
in the parent scope, but this solution doesn't really give an ngChange
method to be implmented and I have been told that watchers are great memory consumers.
我也可以在父作用域中对 foo
使用观察者,但是这个解决方案并没有真正提供要实现的 ngChange
方法,我被告知观察者是伟大的记忆消费者.
Is there a way to make ngChange
be executed synchronously without a timeout or a watcher?
有没有办法让 ngChange
在没有超时或观察者的情况下同步执行?
Example: http://plnkr.co/edit/8H6QDO8OYiOyOx8efhyJ?p=preview
如果你需要 ngModel
你可以在 ngModelController
上调用 $setViewValue
>,它隐式地评估 ng-change
.链接函数的第四个参数应该是 ngModelCtrl.以下代码将使 ng-change
适用于您的指令.
link : function(scope, element, attrs, ngModelCtrl){
scope.updateModel = function(item) {
ngModelCtrl.$setViewValue(item);
}
}
In order for your solution to work, please remove ngChange and ngModel from isolate scope of myDirective.
为了使您的解决方案起作用,请从 myDirective 的隔离范围中删除 ngChange 和 ngModel.
Here's a plunk: http://plnkr.co/edit/UefUzOo88MwOMkpgeX07?p=preview