在我的 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/