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

Angular JS Factory shared in two controllers does not update value

本文关键字:Factory JS Angular 更新 共享 两个 控制器      更新时间:2023-09-26

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控制器中更新。

我错过了什么。

谢谢你的帮助。

它不会更新,因为当你进行时

$scope.selectedStore = currentCustomer.customerID;

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

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

$scope.selectedStore = currentCustomer;

然后使用CCD_ 5。

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

为了更好的可读性和理解性,我对Factory实例进行了一些小的重构-

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

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

这是另一种方法。

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

  1. 使用$rootScope
  2. 通过使用Angularjs中创建自定义服务的机制之一。这些是。。。a) 工厂方法b) Value方法c) 服务方法或d) 提供方法

在本文中,我们将使用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();
      });
});