AngularJs - 如何知道控制器是否完成初始化
问题描述:
我有一个服务,它加载一个文件,然后使用控制器来更新视图。
如果我使用this.loadListAsync那么广播是无用的,因为控制器还没有存在,另一方面,如果我使用$发射的方法它效果很好,我觉得我缺少的东西在这里,$发射不是为了那个通用AngularJs - 如何知道控制器是否完成初始化
var mod= angular.module('mod1', []);
mod.service('modModel', ['$rootScope',function ($rootScope) {
// here is how i know the controller finished initialization
$rootScope.$on('modController', function(ev, data){
data.loadListAsync();
})
this.loadListAsync = function(){
$.ajax({
url:'mainapp/dashboardList.js',
type:'GET',
cache:false,
dataType: "script",
success :this.broadcast
})
}
this.broadcast= function(){
this.list = list; // list is loaded from the async call
$rootScope.$broadcast('modModel::list', list);
}
// this.loadListAsync(); // this line is not working because the controller is not initialized yet
}]);
mod.controller('filtersController', ['$scope', 'sharedData', 'angularLoad','modModel', function ($scope, sharedData, angularLoad, modModel) {
$scope.$on(''modModel::list', function(event, list) {
$scope.list = list;
doThings();
});
$scope.$emit('modController',modModel)
})
答
您有多种选择,一种是$ emit方法。您可以通过传递唯一的事件名称(例如“loaded ::”)来进一步优化它,以确保您获得正确的通知。在收到通知时注册处理程序。 $ on提供注销函数作为$ on的返回值。看看这里$的返回值angular doc for $on
但为什么不简单地传递一个回调函数。你可以包含一个“this”上下文,然后在this.broadcast
内调用xyz.call(this_var, ... callback params)
?