我是AngularJS的新手,我在使用范围变量方面遇到了一些麻烦。
这是一个示例代码。我想知道为什么使用ng-repeat它会显示$ scope.currencies的值,但是当我尝试从JS(console.log($ scope.currencies))访问时,它返回" undefined& #34;
<!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>
&#13;
我认为我的范围出现了问题,有人能给我一些线索吗?
答案 0 :(得分: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);