角度控制器与服务的通信

时间:2014-07-19 16:39:16

标签: javascript angularjs

我想与另一个人沟通控制器。

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

我想在html视图中使用MessageAggregator服务数据。

<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>

工作代码为here jsfiddle

<h3>message: {{message}}</h3>  not populated and working
<h3>info: {{info}}</h3> is working

2 个答案:

答案 0 :(得分:2)

您应该在模块中制作控制器

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

答案 1 :(得分:1)

您需要明确地为MessageAggregator.message对象添加监听侦听器:

$scope.$watch(function() { return MessageAggregator.message; },
  function(newVal, oldVal) { $scope.message = newVal; });

这是Example

或者您应该更改service.setMessage功能,如下所示,以保留message对象引用:

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