AngularJS广播混乱

时间:2014-02-07 09:46:39

标签: javascript angularjs

我有一个关于向儿童范围对象广播的问题。我有以下工厂:

app.factory('mySharedService', function($rootScope) {
var sharedService = {};

sharedService.alertArray = [];

sharedService.prepForBroadcast = function(alertArray) {
    this.alertArray = alertArray;
    this.broadcastItem();
};

sharedService.broadcastItem = function () {
    $rootScope.$broadcast('handleBroadcast');
};

return sharedService;
});

以下是我父控制器的片段:

app.controller('CreateController', function ($scope, mySharedService) {

mySharedService.prepForBroadcast($scope.alerts);

});

这是我儿童控制器的片段:

app.controller('ListController', function ($scope, mySharedService) {

$scope.alerts = [];

$scope.$on('handleBroadcast', function () {
    $scope.alerts = mySharedService.alertArray;
});

});

我还将以下广播对象注入我的控制器:

ListController.$inject = ['$scope', 'mySharedService'];
CreateController.$inject = ['$scope', 'mySharedService'];

我的问题: 当从父控制器调用broadcastItem方法时,它会很好地初始化数组,但是$ scope。$ on中的handleBroadcast方法永远不会被调用。我认为这个方法应该由工厂内的$ rootScope。$ broadcast调用?我有什么遗漏吗?

1 个答案:

答案 0 :(得分:1)

可能会发生这种情况,因为父控制器在子控制器完成加载之前调用服务。尝试添加虚拟超时:

 $timeout(function () {
   mySharedService.prepForBroadcast($scope.alerts);
 }, 0);

工作示例:

<强> JS

演示 Fiddle

var app = angular.module('myModule', []);

function ParentCtrl($scope, $timeout, mySharedService) {

    console.log('firstCtrl');

    $scope.alerts = "Im alert";

     $timeout(function () {
       mySharedService.prepForBroadcast($scope.alerts);
    }, 0);    


}

function ChildCtrl($scope, mySharedService) {

     console.log('secondCtrl');

    $scope.alerts = [];

$scope.$on('handleBroadcast', function () {



    $scope.alerts = mySharedService.alertArray;
});
}

app.factory('mySharedService', function($rootScope) {
var sharedService = {};

sharedService.alertArray = [];

sharedService.prepForBroadcast = function(alertArray) {
    this.alertArray = alertArray;
    this.broadcastItem();
};

sharedService.broadcastItem = function () {
    $rootScope.$broadcast('handleBroadcast');
};

return sharedService;
});

<强> HTML

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl"> 
        <pre>{{alerts}}</pre>
    </div>
</div>