mab
mab

Reputation: 176

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 ?

Upvotes: 0

Views: 2444

Answers (1)

Marcelo Myara
Marcelo Myara

Reputation: 3011

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);

Upvotes: 1

Related Questions