简体   繁体   English

如何在循环内动态创建Angular手表

[英]How to dynamically create Angular watches inside a loop

I want to be able to dynamically create angular watches on one or more model attributes. 我希望能够在一个或多个模型属性上动态创建有角度的手表。 To that end I've tried something such as the following: 为此,我尝试了以下操作:

var fields = ['foo', 'bar'];
for (var i=0, n=fields.length; i<n; i++) {
    $scope.$watch('vm.model.' + fields[i], function(newValue, oldValue) {
        console.log(fields[i]); //always 'bar'
        //logic that was not giving the expected results
    });
}

However this was always working with the last element of the array on every iteration of the loop. 但是,这总是在循环的每次迭代中都使用数组的最后一个元素。 I've seen this behavior when working with asynchronous code before, could that be at play here. 我以前使用异步代码时已经看到过这种行为,这可能在这里起作用。 If so, how to solve? 如果可以,该如何解决?

This is because "after a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync ) to initialize the watcher" -- see the documentation and search for the first instance of $watch in the page. 这是因为“在将观察者注册到范围之后,将异步调用监听者fn(通过$evalAsync )以初始化观察者” - 请参阅文档并在页面中搜索$ watch的第一个实例。

With that in mind it should be easy to resolve by delegating to another function on each iteration of the loop, as follows: 考虑到这一点,应该在每次循环迭代时通过委派另一个函数来轻松解决,如下所示:

var fields = ['foo', 'bar'];
for (var i=0, n=fields.length; i<n; i++) {
    createWatch(fields[i]);
}
function createWatch(field) {
    $scope.$watch('vm.model.' + field, function(newValue, oldValue) {
        console.log(field); //'foo' on first iteration, 'bar' on next
        //logic that should now give the expected result
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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