2014-02-07 78 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>