两个控制器共享的Angular JS Factory不会更新值

时间:2015-11-20 17:32:56

标签: javascript angularjs

Angular的新手,请原谅我,但我将此作为我的index.html:

<body>
    <div data-ng-controller="storeList">
        <select ng-model="selectedItem" ng-options="c.CustomerID as c.CustomerName for c in customers"
        ng-change="changeCust(selectedItem)">
            <option value="">Select Store</option>
        </select>
    </div>

    <div data-ng-controller="storeInfo">
        Selected Store is: {{selectedStore}}
    </div>
</body>

这是我的js:

var storeApp = angular.module('storeApp',[])
storeApp.factory('currentCustomer',function($http) {
return {
    customerID :0,
    getCustomers: function () {
        console.log("in get")
        return [{CustomerID:1,CustomerName:'Store 1'},
                {CustomerID:2,CustomerName:'Store 2'},
                {CustomerID:3,CustomerName:'Store 3'}]

                }
    }


});


    storeApp.controller('storeList',function($scope,$http,currentCustomer) {
    $scope.customers = currentCustomer.getCustomers()


    $scope.changeCust = function changeCust(id) {
        console.log("Changing ID from: "+ currentCustomer.customerID)
        currentCustomer.customerID = id
        console.log("ID Is now: " + currentCustomer.customerID)
    }

    });
    storeApp.controller('storeInfo',function($scope,currentCustomer) {
    console.log("Setting up storeInfo")
    $scope.man = 'Rob';
    $scope.selectedStore = currentCustomer.customerID;
});

当我更改选择时,currentCustomer.customerID会更改,但不会在storeInfo控制器中更新。

我错过了什么。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

它不会更新,因为当你做

$scope.selectedStore = currentCustomer.customerID;

您创建的新属性selectedStore的值等于currentCustomer.customerID,但它们之间没有连接(没有引用)。原始更改时,它不会反映在第二个。

简单的解决方案是使用对象引用:

$scope.selectedStore = currentCustomer;

然后使用{{selectedStore.customerID}}

答案 1 :(得分:0)

这两个绑定不适用于原始数据类型,因为没有引用绑定它们并监听它们的更改。 您可以将currentCustomer对象分配给selectedStore范围变量,这样您就可以监听两个控制器中的更改。

我对Factory实例进行了一些小的重构,以提高可读性和理解力 -

&#13;
&#13;
var storeApp = angular.module('storeApp',[]);
storeApp.factory('currentCustomer',function() {
    var customerId = 0;

    function getCustomerId()
    {
        return customerId;
    }

    function setCustomerId(id)
    {
        customerId = id;
    }

    return {
        getCustomerId : getCustomerId,
        setCustomerId : setCustomerId,
        getCustomers: function () {
            console.log("in get")
            return [{CustomerID:1,CustomerName:'Store 1'},
                {CustomerID:2,CustomerName:'Store 2'},
                {CustomerID:3,CustomerName:'Store 3'}]

        }
    }


});


storeApp.controller('storeList',function($scope,$http,currentCustomer) {
    $scope.customers = currentCustomer.getCustomers();


    $scope.changeCust = function changeCust(id) {
        console.log("Changing ID from: "+ currentCustomer.getCustomerId())
        currentCustomer.setCustomerId(id);
        console.log("ID Is now: " + currentCustomer.getCustomerId())
    }

});
storeApp.controller('storeInfo',function($scope,currentCustomer) {
    console.log("Setting up storeInfo");
    $scope.man = 'Rob';
    $scope.selectedStore = currentCustomer;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="storeApp">
<div data-ng-controller="storeList">
    <select ng-model="selectedItem" ng-options="c.CustomerID as c.CustomerName for c in customers"
            ng-change="changeCust(selectedItem)">
        <option value="">Select Store</option>
    </select>
</div>

<div data-ng-controller="storeInfo">
    Selected Store is: {{selectedStore.getCustomerId()}}
</div>
</body>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果仍然想要使用 $ scope.selectedStore = currentCustomer.customerID;

这是另一种方法。

Angularjs中的控制器间通信可以使用以下机制实现。

  1. 使用$ rootScope
  2. 使用Angularjs中创建自定义服务的机制之一。 这些是...  a)工厂方法  b)价值方法  c)服务方法或  d)提供方法。
  3. 在本文中,我们将使用工厂方法进行Angularjs中的控制器间通信

    请查看帖子 http://yogeshtutorials.blogspot.in/2015/11/inter-controller-communication-in.html

    这是重构的代码

    HTML

      <div data-ng-controller="storeList">
            <select ng-model="selectedItem" ng-options="c.CustomerID as c.CustomerName for c in customers"
            ng-change="changeCust(selectedItem)">
                <option value="">Select Store</option>
            </select>
        </div>
    
        <div data-ng-controller="storeInfo">
            Selected Store is: {{selectedStore}}
        </div>
    

    JS:

    var storeApp = angular.module('storeApp',[])
    storeApp.factory('currentCustomer',function($rootScope) {
      var currentCustomer =  {};
      currentCustomer.customerID = 0;
      currentCustomer.customerName = '';
          currentCustomer.getCustomers =  function () {
              return [{CustomerID:1,CustomerName:'Store 1'},
                      {CustomerID:2,CustomerName:'Store 2'},
                      {CustomerID:3,CustomerName:'Store 3'}]; 
          };
          currentCustomer.setCurrentCustomer = function (custObject) {
            this.customerID = custObject['CustomerID'];
            this.ustomerName = custObject['CustomerName'];
            this.publishChanges();
          }; 
    
          currentCustomer.getCustomerID = function(){
            return this.customerID;
          };
    
          currentCustomer.getCustomerName = function(){
            return this.customerName; 
          };      
          currentCustomer.publishChanges = function() {
                  $rootScope.$broadcast('custDataChangeEvent');
          };
        return currentCustomer; 
    });  
    
        storeApp.controller('storeList',function($scope,$http,currentCustomer,$filter) {
          $scope.customers = currentCustomer.getCustomers();
          $scope.changeCust = function changeCust(id) {
              var filteredCustomerList = $filter('filter')($scope.customers,{CustomerID:id},true);
              var currCustomer = filteredCustomerList[0];
              currentCustomer.setCurrentCustomer(currCustomer);
          };
    
        });
          storeApp.controller('storeInfo',function($scope,currentCustomer) {
          // listen to the events
          $scope.$on('custDataChangeEvent',function(){
           $scope.selectedStore = currentCustomer.getCustomerID();
          });
    });