Javascript 由于异步调用,angularJS数据不可用
这是我的控制器:Javascript 由于异步调用,angularJS数据不可用,javascript,jquery,html,angularjs,Javascript,Jquery,Html,Angularjs,这是我的控制器: function TestCtrl ($scope, sharedProperties, $resource){ var userDataProfile = sharedProperties.getUserDataProfile(); var userCreatedBoard = $resource('/boards?owner=:owner'); userCreatedBoard.query({'owner':userDataProfile.id},
function TestCtrl ($scope, sharedProperties, $resource){
var userDataProfile = sharedProperties.getUserDataProfile();
var userCreatedBoard = $resource('/boards?owner=:owner');
userCreatedBoard.query({'owner':userDataProfile.id}, function (result) {
console.log(result);
});
}
现在的问题是
sharedProperties。在调用第三方服务及其异步服务之后调用setUserDataProfile()
。因此,当绑定TestCtrl
时,userDataProfile
实际上是空的。我如何处理这种情况,以便在调用sharedProperties.setUserDataProfile()
并从第三方服务为变量分配了一个值后,只有我的控制器才能绑定?我想您应该看看解决方案:
这允许您在实例化控制器并触发routeChangeSuccess事件之前加载所有数据
在公园里 像这样将变量传递到Angular.js控制器是没有意义的,这就是Scope变量的用途 试试这个
window.activeTestCtrls = [];
window.sharedProperties = [];
function TestCtrl ($scope, $resource){
if (window.sharedProperties) this.createUserData(window.sharedProperties)
window.activeTestCtrls.push[this];
function createUserData(sharedProperties) {
var userDataProfile = sharedProperties.getUserDataProfile();
var userCreatedBoard = $resource('/boards?owner=:owner');
userCreatedBoard.query({'owner':userDataProfile.id}, function (result) {
console.log(result);
}
});
// and when you get your sharedproperties
function gotSharedProperties(sharedProperties) {
$.each(activeTestControllers, function(index,value) {
activeTestControllers[index].createUserData(sharedProperties)})
}
}
您是否使用$routeprovider?非常好。正是我需要的。