角.controller()。运行之前运行()AngularJS [英] Angular .controller() runs before .run() AngularJS
问题描述
我有.RUN(内调用Ajax)加载一个变量到$ rootScope,需要在与视图相关联的控制变量。
有时,刷新(F5)由.controller加载那里的时候是里面什么也没有$ rootScope.SuperCategories。
I have an ajax call inside the .run() that loads a variable into the $rootScope That variable is needed in the controller associated with a view. Sometimes on refresh (F5) by the time the .controller is loading there is nothing inside $rootScope.SuperCategories.
sampleApp.factory('SuperCategoryService', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope){
var SuperCategoryService = {};
SuperCategoryService.SuperCategories = $rootScope.SuperCategories;
alert ($rootScope.SuperCategories);
return SuperCategoryService;
}]);
sampleApp.run(function($rootScope, $q, $http) {
var req = {
method: 'POST',
url: 'SuperCategoryData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
$rootScope.SuperCategories = [];
$rootScope.GetSuperCategories = function () {
var defer = $q.defer();
$http(screq).then(function(response) {
$rootScope.SuperCategories = response.data;
//alert ($rootScope.SuperCategories);
defer.resolve($rootScope.SuperCategories);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
}
$rootScope.GetSuperCategories();
});
如何修复这个bug。
How to fix this bug.
推荐答案
注意:这是不直接回答你的问题。
我只是试图重写codeA点点的方式利用的承诺和工厂更常见的方式,可能是它会给你一些想法什么可以改进,使异步code的工作更predictably。
NB: this is not directly answer to you question. I've just tried to rewrite your code a little bit in a way to utilize promises and factory more common way, may be it will give you some ideas what can be improved to make the async code work more predictably.
控制器通话工厂以获取数据,并在无极解决你有你的数据 $ rootScope .SuperCategories
Controller calls factory to get the data, and when Promise is resolved you have you data in $rootScope.SuperCategories
sampleApp.factory('SuperCategoryService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'SuperCategoryData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var SuperCategoryService = {};
SuperCategoryService.SuperCategories = function () {
var defer = $q.defer();
$http(screq).success(function(response) {
defer.resolve(response);
});
return defer.promise;
}
return SuperCategoryService;
}]);
sampleApp.controller('myController', ['$scope', 'SuperCategoryService', function($scope, SuperCategoryService) {
SuperCategoryService.SuperCategories().then(function(data){
$rootScope.SuperCategories = data;
});
});
这篇关于角.controller()。运行之前运行()AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!