繁体   English   中英

$ rootScope。$ watchCollection无法正常工作angularjs

[英]$rootScope.$watchCollection is not working angularjs

我试图在我的代码中使用$ rootScope。$ watchCollection从控制器A更新控制器B中的数据。 但我没有取得任何成功。 由于我的应用程序此时卡住了,所以我正在寻求您的帮助,以便我可以知道我在哪里出错了。

控制器B:-

  app.controller('MenuCtrl', function($scope, LocalStorage, $stateParams, $rootScope) { $scope.user = {}; $scope.user.userName = LocalStorage.getData("userName"); $scope.user.profilePic = LocalStorage.getData("userProfile"); $rootScope.$watchCollection(function(n, o) { if (n !== o) { var list = $rootScope.wholecartList; alert("Length " + list.length); } }); }); 

控制器A:-

 app.controller('ProductCtrl', function($http, $scope, $ionicPopup, $state, $ionicHistory, $ionicLoading, DataService, LocalStorage, $stateParams, ProductId, DuplicateCheck, $rootScope) { $scope.productList = DataService.getProducts(); $scope.getProductId = function(productId) { ProductId.addProductId(productId); $state.go("app.products-details"); } var cartList = []; $scope.cartListItems = function(product) { if (cartList.length > 0) { if (!DuplicateCheck.getProducts(product.product_id, cartList)) { cartList.push(product); } } else { cartList.push(product); } $rootScope.wholecartList = cartList; } }); 

任何帮助将不胜感激谢谢。

之后,您需要更新$ rootScope(例如,运行应用周期);否则,您需要更新$ rootScope。

 app.controller('ProductCtrl', function($http, $scope, $ionicPopup, $state, $ionicHistory, $ionicLoading, DataService, LocalStorage, $stateParams, ProductId, DuplicateCheck, $rootScope) { $scope.productList = DataService.getProducts(); $scope.getProductId = function(productId) { ProductId.addProductId(productId); $state.go("app.products-details"); } var cartList = []; $scope.cartListItems = function(product) { if (cartList.length > 0) { if (!DuplicateCheck.getProducts(product.product_id, cartList)) { cartList.push(product); } } else { cartList.push(product); } $rootScope.wholecartList = cartList; updateRootScope(); } function updateRootScope(){ if(!$rootScope.$$phase){ $rootScope.$apply(); } } }); 

暂无
暂无

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

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