简体   繁体   English

AngularJS作用域变量未定义

[英]AngularJS scope variable undefined

I'm new to AngularJS and i have some trouble using scope variables. 我是AngularJS的新手,使用范围变量时遇到了一些麻烦。

Here's a sample code. 这是示例代码。 I'd like to know why using ng-repeat it shows the values of $scope.currencies, but when i try to access from the JS (console.log($scope.currencies)) it returns "undefined" 我想知道为什么使用ng-repeat会显示$ scope.currencies的值,但是当我尝试从JS(console.log($ scope.currencies))访问时,它返回“未定义”

 <!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> 

I think there's something i'm getting wrong about scopes, could anyone give me a clue ? 我认为示波器存在某些问题,有人可以给我一个提示吗?

your console.log statement is outside the .success method. 您的console.log语句在.success方法之外。 As such, it will run right away. 这样,它将立即运行。 You should put it inside the .success method, like this: 您应该将其放入.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);
  });
});

And also, try using $log.debug() instead of console.log(). 另外,尝试使用$ log.debug()而不是console.log()。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM