4

API からデータを取得するサービスを使用しています。

angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
    var getMessages = function() {
        var deferred = $q.defer();

        $timeout(function() {
            deferred.resolve('Hello world!');
        }, 2000);

        return deferred.promise;
    };

  return {
    getMessages: getMessages
  };

});

そして、これらのデータを複数のコントローラーで使用します。

function ControllerA($scope, myService) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function(){
        $scope.message = 'Hello Max';        
    };
}

function ControllerB($scope, myService) {
    $scope.message = myService.getMessages();
    $scope.$watch('message', function(){
       // 'Hello Max'
    }, true);
}

すべてのコントローラーでデータを更新したいのですが、ControllerA で $scope.message を変更しても、ControllerB で変更が発生しません。

編集:「$broadcast」と「$on」の使用を避けたいということです。

何か案は?

ここに jsfiddle があります: http://jsfiddle.net/Victa/McLQD/

4

1 に答える 1

8

を使用$broadcastして にイベントをブロードキャストし、rootScopeを使用$onして、この特定のイベントをリッスンするリスナーを定義できます。

function ControllerA($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function () {
        $scope.message = 'Hello Max';

        $rootScope.$broadcast("HelloEvent", {
            msg: $scope.message
        });
    };
}

function ControllerB($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();

    $rootScope.$on("HelloEvent", function (event, message) {
        $scope.message = message.msg;
    });
}

更新しました:

質問を更新する直前に、上記の解決策を得ました。$broadcast または $on を使用したくない場合は、次の$rootScopように eを介してオブジェクトを共有できます

function ControllerA($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function () {
        $scope.message = 'Hello Max';
        $rootScope.message = 'Hello Max';
    };
}

function ControllerB($scope, myService, $timeout, $rootScope) {
    $scope.message = myService.getMessages();

    $rootScope.$watch('message', function (oldV, newV) {
        if(oldV === undefined && oldV === newV) return;
        $scope.message = $rootScope.message;
    });
}

Demo using broadcast Demo without using broadcast

于 2013-08-12T19:55:24.927 に答える