$ rootScope。$ watchCollection不工作angularjs

时间:2015-10-05 10:34:00

标签: javascript angularjs ionic-framework

我正在尝试在我的代码中使用$ 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;
	}

});

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

1 个答案:

答案 0 :(得分:0)

在此之后,您需要更新$ 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();
            }
        }
});