AngularJS:两个控制器之间通信的正确方式

时间:2016-04-20 11:24:55

标签: angularjs

我正在寻找人们如何编写代码来在两个控制器之间进行通信。我有一个代码正在工作但不确定方法是好的还是标准的。 所以请查看代码并告诉我应该遵循两个控制器之间的通信方法。

<body ng-app="app">
  <div ng-controller="firstCtrl">
    controller 1
<select ng-options="item for item in items" ng-model="mdl"> 
</select> 
  <button ng-click="updateAlphabets()">update</button>
  </div>

  <div ng-controller="secondCtrl">
     controller 2
<select ng-options="item for item in items" ng-model="mdl"> 
</select>
    <button ng-click="updateItems()">update</button>
  </div>
</body>

function firstFunc($scope){
  $scope.items=["one","two","three"];
  $scope.updateAlphabets=function(){
    secondFunc($scope);
    $scope.updateItems();
  };
}

function secondFunc($scope){
  $scope.items=["apple","boy","cat"];
  $scope.updateItems=function(){
    $scope.items=["a","b","c"];
  };
}

angular.module("app",[]).controller("firstCtrl",["$scope",
firstFunc]).controller("secondCtrl",["$scope",
secondFunc]);

寻找建议,因为我现在正在学习角度,而且我是在大多数人遵循的正确方法和模式之后。感谢

1 个答案:

答案 0 :(得分:2)

这个问题很可能是重复的。关于这个主题的最受欢迎的答案谈到了很多关于使用事件在控制器之间进行通信的问题。我不认为事件是正确的方法。

正确答案是使用共同服务。

您可以将服务创建为简单的值存储,也可以使用更优雅的模式(如observable)并在控制器之间传递信息。

function ValueStore() {
    this._valueObject = {foo: 'initial value'};
}

ValueStore.prototype.getValueObject = function() {
    return this._valueObject;
}

ValueStore.prototype.setValueObject = function(valueObject) {
    this._valueObject = valueObject;
}

angular.module('app').service('valueStore', ValueStore);

然后在您的控制器中,您可以注入此服务并获取和设置控制器之间的值。您可能希望传递对象而不是值,以便您可以通过引用获取更新的值。

您的实现不需要与上述代码匹配。如果您愿意,可以使用属性。我们的想法是使用服务传递数据。

<强>更新 对一个非常相似的问题的回答How to communicate between controllers of two different modules in AngularJs有一个使用服务和对象引用在两个控制器之间进行通信的工作示例。