【问题标题】:angularJS data not available due to async call由于异步调用,angularJS 数据不可用
【发布时间】:2013-07-19 21:11:54
【问题描述】:

这是我的控制器:

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() 在调用 3rd 方服务及其异步之后被调用。因此,当绑定TestCtrl 时,userDataProfile 实际上为空。我该如何处理这种情况,以便在调用 sharedProperties.setUserDataProfile() 并从 3rd 方服务为变量分配一个值之后,只有我的控制器应该被绑定?

【问题讨论】:

  • 你在使用 $routeprovider 吗??

标签: javascript jquery html angularjs


【解决方案1】:

我想你想看看解决:

http://www.youtube.com/watch?v=Kr1qZ8Ik9G8

这允许您在实例化控制器并触发 routeChangeSuccess 事件之前加载所有数据。

angular docs

【讨论】:

  • 优秀。正是我需要的。
【解决方案2】:

像这样将变量传递给 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)})
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2014-12-10
    • 2014-06-23
    相关资源
    最近更新 更多