我是angular-js的新手。我有两个控制器(welcomeContoller,productController),并且都在工厂内处理相同的模型。工厂值未在模型中更新......我做错了什么?
当模型通过一个控制器(productController)更新时,它应该反映另一个控制器中的更新。 (welcomeContoller)
但它现在没有发生。
HTML代码:
<body ng-app="myApp">
<div ng-controller="welcomeContoller">
{{totalProductCnt}}
</div>
<div ng-controller="productController">
<div class="addRemoveCart">
<span class="pull-left glyphicon glyphicon-minus" ng-click="removeProduct()"></span>
<span class="pull-right glyphicon glyphicon-plus" ng-click="addProduct(1)"></span>
</div>
</div>
JS代码
var myApp = angular.module("myApp", ['ui.bootstrap']);
myApp.factory("productCountFactory", function() {
return {
totalProducts:0
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory)
{
$scope.totalProductCnt = productCountFactory.totalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.totalProducts++;
alert(productCountFactory.totalProducts);
};
$scope.removeProduct = function() {
if(productCountFactory.totalProducts >=1)
productCountFactory.totalProducts--;
alert(productCountFactory.totalProducts);
};
});
的addProduct命令被称为totalProductCnt正在显示为零即使经过。我想显示每个增量的值。
你可以为此设置一个plunkr吗? –
我已经添加了一个plunkr链接。 – Paqman