javascript - AngularJS 范围未定义

标签 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) 直接访问它时,我得到“未定义”。

为什么我不能直接访问它?我需要访问它,因为 additonalDataService 取决于 childrenDataService 的默认选择。

谢谢你的帮助

最佳答案

在您的情况下,当您尝试获取 $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 ,您可以使用 promise 链:

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;
})

关于javascript - AngularJS 范围未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496002/

相关文章:

javascript - 在 ng-click 中使用 "this"

php - 将客户端设备时钟与服务器时钟进行精确到毫秒的比较

javascript - 使用 groupBy 对数组进行分组

c - 尽管分配了堆,但一旦函数退出,内存就会越界?

javascript - Konva.js : simultaneously run tweens look out of sync

javascript - 更改图例符号的大小

javascript - 在angularjs中使用ng-repeat时如何将当前月份保持在列表顶部

javascript - Angular ui.router 重新加载模板

javascript - Javascript 函数外部的常量变量

javascript - angular.module 和 window.angular.module 之间有什么区别吗?