我在父控制器的http.get()方法内定义了$ scope变量。我不能直接从孩子控制器访问它,因为它说未定义。当我使用Watch函数从我的子控制器访问这些范围变量时,它的工作正常。但是,对于更多数量的范围变量我该如何使用手表功能?或者,另一种方法可以在不使用手表的情况下做到这一点? 我已经更新了我的小提琴这里click here fiddle for accessing more number of parent scope variables使用手表从子控制器访问父范围
function ParentCtrl($scope, $http) {
$scope.cities = ["NY", "Amsterdam", "Barcelona"];
// $scope.example1 = $http.get('/echo/json');
$http.get('/echo/json').then(function(value) {
\t $scope.example2 = value.status;
\t \t });
$http.get('/echo/json/error').then(null,function(value) {
$scope.example3 = value.status;
});
$http.get('/echo/json').success(function(data, status, headers, config) {
$scope.example4 = status;
});
$http.get('/echo/json/error').error(function(data, status, headers, config) {
$scope.example5 = status;
});
$http.get('/echo/json/error').catch(function(value) {
$scope.example6 = value.status;
});
}
function ChildCtrl($scope) {
$scope.parentcities = $scope.$parent.cities;
// console.log("1=="+$scope.example1);//undefined
console.log("2=="+$scope.example2);//undefined
console.log("3=="+$scope.example3);//undefined
console.log("4=="+$scope.example4);//undefined
console.log("5=="+$scope.example5);//undefined
console.log("6=="+$scope.example6);//undefined
/*$scope.$watch("example1", function(example1) {
if(angular.isDefined(example1)){
console.log("1_watch=="+$scope.example1); //Defined
}
});*/
$scope.$watch("example2", function(example2) {
if(angular.isDefined(example2)){
console.log("2_watch=="+$scope.example2); //Defined
}
});
$scope.$watch("example3", function(example3) {
if(angular.isDefined(example3)){
console.log("3_watch=="+$scope.example3); //Defined
}
});
$scope.$watch("example4", function(example4) {
if(angular.isDefined(example4)){
console.log("4_watch=="+$scope.example4); //Defined
}
});
$scope.$watch("example5", function(example5) {
if(angular.isDefined(example5)){
console.log("5_watch=="+$scope.example5); //Defined
}
});
$scope.$watch("example6", function(example6) {
if(angular.isDefined(example6)){
console.log("6_watch=="+$scope.example6); //Defined
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl as vm">
{{$parent.cities}}
</div>
</div>
你的小提琴链接不是超链接。你可以编辑 – Maverick
@Maverick你可以检查现在plz与点击这里链接 – VVijay