更新阵列时AngularJS不刷新ngRepeat [英] AngularJS not refreshing ngRepeat when updating array

查看:235
本文介绍了更新阵列时AngularJS不刷新ngRepeat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有严重的麻烦了解AngularJS有时。所以,我有我的控制器如

I'm having serious troubles understanding AngularJS sometimes. So I have a basic array in my controller like

$scope.items = ["a","b","c"]

我ngRepeating在我的模板在项目数组NG重复=中的项项。超级straightfoward至今。一对夫妇UX的行动后,我想推一些新的东西,我的数组。

I'm ngRepeating in my template over the items array ng-repeat="item in items". Super straightfoward so far. After a couple of UX actions, I want to push some new stuff to my array.

 $scope.items.push("something");

那么,50%的时间,新元素被添加到图。但另外50%,没有任何反应。它就像超级沮丧; BC如果我换了$范围之内。$适用(),我得到了一个$摘要已在进行中的错误。该包装到$超时没有帮助的。

So, 50% of the time, the new element is added to the view. But the other 50%, nothing happens. And it's like super frustrating; bc if I wrap that within $scope.$apply(), I got a "$digest already in progress" error. Wrapping that into $timeout doesn't help either.

而当我检查使用Chrome扩展我的元素范围;我可以看到新的数据是存在的,在$ scope.items值是正确的。但视图只是没有采取并称DOM的照顾。

And when I inspect my element scope using the Chrome extension; I can see the new data is there and the $scope.items value is correct. But the view is just not taking care of adding that to the DOM.

谢谢!

推荐答案

您正在修改角的 $消化周期的50%的时间以外的范围。

You are modifying the scope outside of angular's $digest cycle 50% of the time.

如果有回调这是不从angularjs; (posibbly jQuery的)。你需要调用 $适用强制 $消化周期。
但你不能叫 $适用,而在 $消化周期,因为每一个改变你做会自动已反映出来。

If there is a callback which is not from angularjs; (posibbly jquery). You need to call $apply to force a $digest cycle. But you cannot call $apply while in $digest cycle because every change you made will be reflected automatically already.

您需要知道什么时候回调的角度是不是和应该叫 $适用只有

You need to know when the callback is not from angular and should call $apply only then.

如果你不知道,不能够学习,这里是一个巧妙的方法:

If you don't know and not able to learn, here is a neat trick:

var applyFn = function () {
    $scope.someProp = "123";
};
if ($scope.$$phase) { // most of the time it is "$digest"
    applyFn();
} else {
    $scope.$apply(applyFn);
}

这篇关于更新阵列时AngularJS不刷新ngRepeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆