Reputation: 2451
i was looking how people write code to communicate between two controller. i got one code which is working but not sure the approach is good or standard. so review the code and tell me should we follow the approach to communicate between two controller.
<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]);
looking for suggestion because i am learning angular now and i am after right approach and pattern where majority of people follow. thanks
Upvotes: 0
Views: 1562
Reputation: 16300
This question is most likely a duplicate. The most upvoted answer on this subject talks about a lot about using events to communicate between controllers. I don't think events are the correct approach.
The correct answer is with a common service.
You can create an service as a simple value store or use more elegant patterns like observables and pass information between controllers.
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);
Then in your controllers you can inject this service and get and set the values between controllers. You probably want to pass objects rather than values so that you can then just get the updated values by reference.
Your implementation doesn't need to match the above code. You can use properties if you wish. The idea is you use a service to pass data.
UPDATE This answer How to communicate between controllers of two different modules in AngularJs to a very similar question has a working example of communicating between two controllers using a service and object references.
Upvotes: 2