Angularjs 模型中未更新工厂值…我做错了什么?
我是新手。我有两个控制器(welcomeContoller、productController),它们都在工厂内处理同一型号 当模型由一个控制器(productController)更新时,它应该在另一个控制器中反映更新。(welcomeContoller) 但现在还没有发生 HTML代码:Angularjs 模型中未更新工厂值…我做错了什么?,angularjs,Angularjs,我是新手。我有两个控制器(welcomeContoller、productController),它们都在工厂内处理同一型号 当模型由一个控制器(productController)更新时,它应该在另一个控制器中反映更新。(welcomeContoller) 但现在还没有发生 HTML代码: <body ng-app="myApp"> <div ng-controller="welcomeContoller"> {{totalProductCnt}} </di
<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>
即使在调用addProduct之后,totalProductCnt也显示为零。我想显示每个增量的值
您的welcomeController中的totalProductCnt不会更新,因为在创建控制器时只分配了一次 可以使用多种解决方案刷新显示的值。在工厂为您的产品使用吸气剂:
myApp.factory("productCountFactory", function() {
var totalProducts = 0;
return {
getTotalProducts: function() {
return totalProducts;
},
addProduct: function() {
totalProducts++;
},
removeProduct: function() {
totalProducts--;
}
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.getTotalProducts = productCountFactory.getTotalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.addProduct();
};
$scope.removeProduct = function() {
if (productCountFactory.getTotalProducts() >= 1)
productCountFactory.removeProduct();
};
});
并相应地更新视图:
<div ng-controller="welcomeContoller">
{{getTotalProducts()}}
</div>
{{getTotalProducts()}}
将工厂对象引用放在范围上:
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.productCountFactory = productCountFactory;
});
观察对象的属性
{{productCountFactory.totalProducts}}
这个
通过在作用域上放置一个引用,在每个摘要周期中,观察者都会查找属性的值,并在发生更改时更新DOM。您能为此设置一个plunkr吗?我添加了一个plunkr链接。
{{productCountFactory.totalProducts}}