2015-05-07 105 views
0

我是AngularJS的新手,我在使用范围变量时遇到了一些麻烦。AngularJS范围变量undefined

下面是一个示例代码。我想知道为什么使用ng-repeat它显示$ scope.currencies的值,但是当我尝试从JS(console.log($ scope.currencies))访问时,它返回“undefined”

<!DOCTYPE html> 
 
<html> 
 
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
 
<body> 
 

 
<div ng-app="myApp" ng-controller="appCtrl"> 
 

 
<ul> 
 
    <li ng-repeat="x in currencies"> 
 
    {{ x }} 
 
    </li> 
 
</ul> 
 

 
</div> 
 

 
<script> 
 
var app = angular.module('myApp', []); 
 
app.controller('appCtrl', function($scope, $http) { 
 
    $http.get("http://localhost:8080/currencies") 
 
    .success(function (response) {$scope.currencies = response;}); 
 

 

 
    console.log("currencies are "+$scope.currencies); 
 
}); 
 
</script> 
 

 
</body> 
 
</html>

我觉得有什么东西我越来越错范围,任何人都可以给我一个线索?

+0

您的console.log正在运行,然后$ http.get的响应可以触发.success方法。在那个时候,$ scope.currencies仍然是未定义的。 –

+0

您对$ q/$ http/promise有错。 – dizel3d

回答

1

您的console.log语句不在.success方法中。因此,它会马上运行。你应该把它放在.success方法里面,像这样:

var app = angular.module('myApp', []); 
app.controller('appCtrl', function($scope, $http) { 
    $http.get("http://localhost:8080/currencies") 
    .success(function (response) { 
     $scope.currencies = response; 
     console.log("currencies are "+$scope.currencies); 
    }); 
}); 

而且还尝试使用$ log.debug(),而不是执行console.log的()。

app.controller('appCtrl', function($scope, $http, $log) { 
... 
    .success(function (response) { 
     $scope.currencies = response; 
     $log.debug("currencies are "+$scope.currencies); 
+0

感谢您的回答。其实我认为我没有足够明确,我已经尝试了你的建议,并且它运行良好,但是我真正想要做的是在.success方法之外访问我的控制器中的$ scope.currencies(我使用了控制台.log只是一个测试)。我想我不太清楚承诺是如何工作的,但现在,如果我只是了解如何从控制器主体访问$ scope.currencies,必然会使用角度指令来做到这一点,我会很开心。 – mab

+1

好的,让我试着再次帮助你:你可以随时使用scope属性。它们应该与视图上的元素绑定(使用ng数据)。 Angular会小心刷新绑定到属性的任何元素,以反映该属性的任何更改。要想取消它,你可以在你的页面的任何地方放置一个' {{currency}}',并且每次改变$ scope.currencies值时就会自动改变它(就像在.success方法中发生的那样) 。 –

+0

因此,您的console.log将无法执行您期望的操作(以“监视”该属性),因为它将立即运行,并且只会运行一次。它将在运行时获取值,但不会在属性发生任何更改之后获取。 –