fri*_*itz 5 dependencies controller angularjs
我在.run()中有一个ajax调用,它将一个变量加载到$ rootScope中.在与视图关联的控制器中需要该变量.
有时在.controller加载时刷新(F5)时,$ rootScope.user.fedUnit内部没有任何内容导致:
TypeError:无法读取未定义的属性'fedUnit'
有没有什么方法可以延迟加载控制器直到完成.run()之后?似乎无法找到它.
app.run(function($rootScope, $http, $location, SessionFactory, TokenHandler) {
token = TokenHandler.getToken();
if ( token != null ) {
SessionFactory.get( { token : token },
function success(response, responseHeaders) {
$rootScope.user = response;
}
);
}
});
app.controller('UnitController', function($scope, $rootScope, $location, UnitFactory) {
$scope.updateUnits = function () {
UnitFactory.query({fedUnit: $rootScope.user.fedUnit}, function success(response, responseHeaders) { ...
Run Code Online (Sandbox Code Playgroud)
解
$rootScope.foo = $q.defer();
$rootScope.foo.resolve(); when AJAX is done;
$rootScope.foo.promise.then(..) in the controller.
Run Code Online (Sandbox Code Playgroud)
感谢@misterhiller(twitter)
小智 7
功能代码块的解决方案:
app.run(function($rootScope, $http, $q, SessionFactory, TokenHandler) {
$rootScope.ajaxCall = $q.defer();
token = TokenHandler.getToken();
if ( token != null ) {
SessionFactory.get( { token : token },
function success(response, responseHeaders) {
$rootScope.user = response;
$rootScope.ajaxCall.resolve();
}
);
}
});
app.controller('UnitController', function($scope, UnitFactory) {
$scope.ajaxCall.promise.then(function() {
$scope.updateUnits = function () {
UnitFactory.query({fedUnit: $scope.user.fedUnit});
}
});
});
Run Code Online (Sandbox Code Playgroud)
我不在控制器中使用$ rootScope.
| 归档时间: |
|
| 查看次数: |
10286 次 |
| 最近记录: |