AngularJS范围未定义

时间:2016-04-08 09:22:44

标签: javascript angularjs scope angularjs-scope

在我的ControllerA中,我有一个init()函数来加载这些服务:

init(){
childrenDataService.getData($scope.family_id).then(function(result) {
  $scope.childrenName = result;
  $scope.selectedChild = result[0];
})

console.log($scope);
console.log($scope.selectedChild)

//this doesn't work => TypeError: Cannot read property 'id' of undefined
//can't access $scope.selectedChild.id
additonalDataService.getData($scope.selectedChild.id).then(function(result){
  scope.additional = result;
})
}

ChildrenDataService的加载工作正常。我的问题是console.log($ scope)给了我完整的对象。 $ scope.selectedChild属性填充了一个对象。

但是当我尝试通过console.log($ scope.selectedChild)直接访问它时,我得到了#undefined'。

为什么我无法直接访问此内容?我需要访问它,因为additonalDataService依赖于childrenDataService的默认选择。

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

在您的情况下,当您尝试获取$scope.selectedChild.id时,它确实未定义,因为childrenDataService.getData尚未完成。您可以尝试使用以下方法解决此问题:

init(){
childrenDataService.getData($scope.family_id).then(function(result) {
  $scope.childrenName = result;
  $scope.selectedChild = result[0];
  additonalDataService.getData($scope.selectedChild.id).then(function(result){
      $scope.additional = result;
  })
})

}

更新

如果您的服务返回承诺,您可以使用promise-chaining:

childrenDataService.getData($scope.family_id).then(function(result) {
  $scope.childrenName = result;
  $scope.selectedChild = result[0];
  return additonalDataService.getData(id);
})
.then(function(result){
  $scope.additional = result;
})

答案 1 :(得分:1)

  

有没有一个更好的解决方案,而不是相互分阶段的所有服务?

您可以使用承诺链接

var initPromise = init(){
    //return derived promise
    return (
        childrenDataService.getData($scope.family_id)
            .then(function(result) {
                $scope.childrenName = result;
                $scope.selectedChild = result[0];
                //return for chaining
                return ($scope.selectedChild);
             })
        ;
    );
};
返回的承诺

initPromise.then(function (selectedChild) {
    additonalDataService.getData(selectedChild.id)
        .then(function(result){
             scope.additional = result;
        })
    ;
});

因为调用promise的.then方法会返回一个新的派生promise,所以很容易创建一个promise链。可以创建任何长度的链,并且由于可以使用另一个承诺(将进一步推迟其解析)来解决承诺,因此可以在链中的任何点暂停/推迟承诺的解析。这使得实现强大的API成为可能。 1

答案 2 :(得分:0)

您面临的问题是回调功能。回调意味着稍后再回电它会在完成所有处理之后给出结果。

尝试将所有内容放在回调函数中

试试这个,这可能会有所帮助

init(){
childrenDataService.getData($scope.family_id).then(function(result) {
 $scope.childrenName = result;
 $scope.selectedChild = result[0];

console.log($scope);
console.log($scope.selectedChild)

//this doesn't work => TypeError: Cannot read property 'id' of undefined
//can't access $scope.selectedChild.id
additonalDataService.getData($scope.selectedChild.id).then(function(result){
  scope.additional = result;
  });
 })
}