简体   繁体   中英

AngularJS scope variable undefined

I'm new to AngularJS and i have some trouble using scope variables.

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"

 <!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. As such, it will run right away. You should put it inside the .success method, like this:

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().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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