AngularJS 在更新数组时不刷新 ngRepeat [英] AngularJS not refreshing ngRepeat when updating array

查看:28
本文介绍了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"]

我正在我的模板中重复项目数组 ng-repeat="item in items".到目前为止超级简单.经过几次 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 如果我将其包装在 $scope.$apply() 中,则会出现$digest already in progress"错误.将其包装到 $timeout 中也无济于事.

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% 的时间在修改 angular $digest 循环之外的范围.

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

如果有一个不是来自angularjs的回调;(可能是jquery).您需要调用 $apply 来强制一个 $digest 循环.但是您不能在 $digest 循环中调用 $apply,因为您所做的每个更改都将自动反映.

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.

你需要知道什么时候回调不是来自 angular 并且应该只在那时调用 $apply.

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天全站免登陆