问题描述
所有的,下面我有以下AngularJS。为什么 $ scope.gotData code>不可见呼叫到
外getData.success()
?需要注意的是 $ scope.gotData code>是视图中可见:我可以通过将显示
scope.gotData code>的值
{{} gotData}
我的 index.html的
。
我为什么不能访问 $ scope.gotData code>在我的控制器其他变量?这是关于$范围的详细情况的问题。
getData.js
myApp.factory('的getData',函数($ HTTP){
返回$ http.jsonp('https://foo.com/bar.json')
.success(功能(数据){
返回的数据;
})
.error(功能(错误){
返回ERR;
});
});
MainController.js
myApp.controller('MainController',['$范围','的getData',函数($范围的getData){
getData.success(功能(数据){
$ scope.gotData =数据;
}); $ scope.gotData / *没有定义HERE * /
}]);
的index.html
< HTML和GT;
< HEAD>
<脚本SRC =JS /供应商/ angular.js>< / src目录>
< /头>
<机身NG-应用=MyApp的>
< DIV NG控制器=MainController>
{{} gotData} / *我可以在这里看到的数据* /
< / DIV>
< /身体GT;
< / HTML>
的为什么你不能看到 $ scope.gotData code> > getData.success()
函数是因为 .success()
为 异步的和值,当您尝试访问外 .success不可用()
。这基本上意味着承诺尚未解决。
此外,一旦角的消化周期标识 $ scope.gotData code>填充,它迅速更新视图。这就是为什么你可以看到
$ scope.gotData code>视图的原因
事情会更清楚一个看
在 $ scope.gotData code>
myApp.controller('MainController',['$手表','$范围','的getData',函数($手表,$范围的getData){
getData.success(功能(数据){
$ scope.gotData =数据;
}); $范围。$腕表($ scope.gotData,功能(N,O){
的console.log(新val->中+ N);
的console.log(旧val->中+ O);
})
}]);
All, I have the following AngularJS below. Why is $scope.gotData
not visible outside of the call to getData.success()
? Note that $scope.gotData
is visible to the view: I can display the value of scope.gotData
by placing {{gotData}}
within my index.html
.
Why can I not access $scope.gotData
as a variable elsewhere in my controller? This is a question concerning the details of $scope.
getData.js
myApp.factory('getData',function($http){
return $http.jsonp('https://foo.com/bar.json')
.success(function(data){
return data;
})
.error(function(err){
return err;
});
});
MainController.js
myApp.controller('MainController', ['$scope','getData', function($scope, getData){
getData.success(function(data){
$scope.gotData = data;
});
$scope.gotData /* NOT DEFINED HERE */
}]);
index.html
<html>
<head>
<script src="js/vendor/angular.js"></src>
</head>
<body ng-app="MyApp">
<div ng-controller="MainController">
{{gotData}} /* I CAN SEE THE DATA HERE */
</div>
</body>
</html>
The reason why you cannot see $scope.gotData
outside the getData.success()
function is because .success()
is async and the value is not available when you try to access it outside .success()
. This essentially means that the promise has not been resolved yet.
Moreover, once angular's digest cycle identifies that $scope.gotData
is populated, it quickly updates the view. Thats the reason why you can see $scope.gotData
in the view
Things would be more clear once you put a watch
on $scope.gotData
myApp.controller('MainController', ['$watch','$scope','getData', function($watch,$scope, getData){
getData.success(function(data){
$scope.gotData = data;
});
$scope.$watch($scope.gotData,function(n,o){
console.log("new val-> "+n);
console.log("old val->"+o);
})
}]);
这篇关于未定义的变量内部控制器($范围的问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!