角 - 如何看在我的控制器cookie的值,而不会引起"错误$消化()迭代达到" [英] Angular - How can I watch a cookie value in my controller without causing "Error $digest() iterations reached"
问题描述
我有一个应用程序,用户将项目添加到他们的购物车。如果他们没有登录到该网站的项目都存储在他们的饼干。我想创建的人有多少项目在他们的车一视觉指示器(即的CookieStore),因为它们增加一个项目,一旦更新。
I have an app where users add items to their cart. If they are not logged into the site the items are stored in their cookies. I am trying to create a a visual indicator of how many items the person has in their cart (i.e. cookiestore) that updates as soon as they add an item.
要做到这一点,我有以下code:
To do this I have the following code:
控制器
$scope.temporaryCart = $cookieStore.get('cart').length;
$scope.$watch(function () {
return $cookieStore.get('cart');
}, function () {
$scope.temporaryCart = $cookieStore.get('cart').length;
});
在我的部分我有:
And in my partial I have:
<div class="words">{{temporaryCart || 0}}</div>
如果我不包括 $ $范围看
的车没有及时更新,但是,当我做包含它,我得到:
If I do not include the $scope.$watch
the cart does not update, however, when I do include it, I get:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: function () {\n return $cookieStore.get('cart');\n }"...
这是得到像饼干的东西,从实时更新正确的方法? - 或者我怎么能避免所有的迭代,仍然追踪存储在cookie或数据库的动态更新值
Is this the right approach to get real time updates from things like Cookies - or how can I avoid all of the iterations and still track a dynamically updating value stored in cookies or a database?
推荐答案
要简单地说,你的$观看功能每次都返回不同的对象,因此消化周期从未平息。换句话说,以下为真:
To put simply, your "$watched" function returns a different object every time, and so the digest cycle never settles. In other words, the following is true:
$cookieStore.put("foo", {v: "bar"});
var c1 = $cookieStore.get("foo");
var c2 = $cookieStore.get("foo");
console.log(c1 === c2); // false
(顺便说一句, $的CookieStore
是德precated,但同样会是真实与 $ cookies.getObject
)
(btw, $cookieStore
is deprecated, but the same would be true with $cookies.getObject
)
如果您的必须的使用Cookies来跟踪变量(当然,如果没有一个服务,的localStorage
和的sessionStorage
,在评论中指出,更适合于它),你可以设置一个$手表的属性之一:
If you must use cookies to track variables (certainly, if not a service, localStorage
and sessionStorage
, as noted in comments, are more suited for it), you could set a $watch for one of its properties:
$scope.$watch(function(){
return $cookies.getObject("cart").length;
}, function(v){
$scope.temporaryCart = v;
});
这篇关于角 - 如何看在我的控制器cookie的值,而不会引起&QUOT;错误$消化()迭代达到&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!