Reputation: 6875
I want to communicate controllers with another.
var module = angular.module("app", []);
module.service("MessageAggregator", function(){
var service = {};
service.message = {};
service.setMessage = function(message){
service.message = message;
};
return service;
});
function firstController($scope, MessageAggregator){
$scope.sendRequest = function(){
MessageAggregator.setMessage({type: "FeatureSet"});
};
}
function secondController($scope, MessageAggregator){
$scope.info = MessageAggregator;
$scope.message = MessageAggregator.message;
}
I want to use MessageAggregator service data in html view.
<div ng-app="app">
<div ng-controller="firstController">
<button ng-click="sendRequest()">Request</button>
</div>
<hr/>
<div ng-controller="secondController">
<h3>info: {{info}}</h3>
<h3>message: {{message}}</h3>
</div>
</div>
Working code is here jsfiddle
<h3>message: {{message}}</h3> not populated and working
<h3>info: {{info}}</h3> is working
Upvotes: 0
Views: 101
Reputation: 22478
You need to explicitely add watch listener for MessageAggregator.message
object:
$scope.$watch(function() { return MessageAggregator.message; },
function(newVal, oldVal) { $scope.message = newVal; });
Here is an Example
or you should to change the service.setMessage
function as below to preserve message
object reference:
service.setMessage = function (message) {
for (var prop in message) {
if (message.hasOwnProperty(prop)) {
service.message[prop] = message[prop];
}
for(var prop in service.message){
if(!message.hasOwnProperty(prop)){
delete service.message[prop];
}
}
}
};
Upvotes: 1
Reputation: 33
You should make your controller in your module
module.controller("firstController", function($scope, MessageAggregator){
$scope.sendRequest = function(){
MessageAggregator.setMessage({type: "FeatureSet"});
};
});
module.controller("secondController", function($scope, MessageAggregator){
$scope.info = MessageAggregator;
$scope.message = MessageAggregator.message;
});
Upvotes: 1