【发布时间】:2026-02-02 05:55:01
【问题描述】:
所有,我在下面有以下 AngularJS。为什么$scope.gotData 在对getData.success() 的调用之外不可见?请注意 $scope.gotData 对视图是可见的:我可以通过将 {{gotData}} 放在我的 index.html 中来显示 scope.gotData 的值。
为什么我不能将$scope.gotData 作为控制器中其他地方的变量访问?这是一个关于$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>
【问题讨论】:
标签: javascript angularjs http callback scope