在 angular 中加载后访问父控制器 $scope 数据
Accessing parent controller $scope data after load in angular
我在angular有以下情况:
- 我在 init() 上从数据库加载 json 数据到变量 "data" 并想在子控制器(嵌套)中使用变量 "data"。
- 因为从数据库加载需要一些时间,子控制器中的变量$scope.data输出为"undefined"。
处理这种情况的优雅方法是什么?我是否需要在子控制器内对父级的 init 方法使用承诺?我将不胜感激 :).
// Parent Controller
app.controller('pCTRL', function($scope) {
$scope.init = function(id){}
//sets my variable $scope.data successfully via a rest API
//and for test, sets $scope.x to "blabla"
}
//Child Controller
app.controller('cCTRL', function($scope) {
console.log($scope.x); //outputs blabla properly
console.log($scope.data); // undefined
感谢您的反馈!
一个常见的解决方案是使用观察者。例如:
app.controller('cCTRL', function($scope) {
$scope.$watch('data', function(newVal){
console.log(newVal); // outputs actual value
});
}
仅当您需要在指令中包含逻辑时才需要这样做。如果你只想在 cCTRL
模板中显示 data
你不需要上面的观察者,angular 将在父级更改时更新模板。
我在angular有以下情况:
- 我在 init() 上从数据库加载 json 数据到变量 "data" 并想在子控制器(嵌套)中使用变量 "data"。
- 因为从数据库加载需要一些时间,子控制器中的变量$scope.data输出为"undefined"。
处理这种情况的优雅方法是什么?我是否需要在子控制器内对父级的 init 方法使用承诺?我将不胜感激 :).
// Parent Controller
app.controller('pCTRL', function($scope) {
$scope.init = function(id){}
//sets my variable $scope.data successfully via a rest API
//and for test, sets $scope.x to "blabla"
}
//Child Controller
app.controller('cCTRL', function($scope) {
console.log($scope.x); //outputs blabla properly
console.log($scope.data); // undefined
感谢您的反馈!
一个常见的解决方案是使用观察者。例如:
app.controller('cCTRL', function($scope) {
$scope.$watch('data', function(newVal){
console.log(newVal); // outputs actual value
});
}
仅当您需要在指令中包含逻辑时才需要这样做。如果你只想在 cCTRL
模板中显示 data
你不需要上面的观察者,angular 将在父级更改时更新模板。