2016-03-07 31 views
1

我是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 Link

回答

1

放在范围的工厂对象的引用:

myApp.controller("welcomeContoller", function($scope, productCountFactory) { 

    $scope.productCountFactory = productCountFactory; 

}); 

观察对象的属性。

{{productCountFactory.totalProducts}} 

DEMO on PLNKR

通过在作用域上放置参考,在每个摘要循环中,watcher查找属性的值并在发生更改时更新DOM。

1

的totalProductCnt从welcomeCont [R奥勒没有更新,因为它被分配仅在创建控制器一次。

您可以使用多种解决方案刷新显示的值。因此

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(); 
    }; 
}); 

而且更新视图:在工厂使用的getter你totalProducts

<div ng-controller="welcomeContoller"> 
    {{getTotalProducts()}} 
</div> 

Plunkr Link

+0

你可以为此设置一个plunkr吗? –

+0

我已经添加了一个plunkr链接。 – Paqman