2014-02-07 77 views
1

我有一个关于广播到子范围对象的问题。我有以下工厂: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来调用?有什么我失踪了吗?

+0

您可能想要使用https://github.com/georapbox/angular-PubSub角度模块! – vinesh

回答

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>