0

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

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference? I tried in jsfiddle but same result.
Sorry I think I can't answer your question. @Yuriy Rozhovetskiy 's way may work but I think it's too complecated. I suggest replace <h3>message: {{message}}</h3> to <h3>message: {{info.message}}</h3>, leave the binding/ watching thing to angular
I guess after setMessage(), the $scope.message in secondController is still reference to the old one
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.