Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Good afternoon! Learning Angularjs. Below is the structure of the project. I have a service that reads data from json

var WebKrServices = angular.module('WebKrServices', ['ngResource']);

WebKrServices.factory('DataPlant', ['$resource',
  function($resource){
    return $resource('plants/:plantId.json', {}, {
      query: {method:'GET', params:{plantId:'plants'}, isArray:true}
    });
  }]);

And Controller

var WebKrControllers = angular.module('WebKrControllers', []);

WebKrControllers.controller('PlantsCtrl', ['$scope', 'DataPlant',
  function($scope, DataPlant) {
    $scope.plants = DataPlant.query();
  }]);

which transmits this information to the html

<div ng-repeat="plant in plants">
  <h2 class="text-center">{{plant.name}}</h2>
  <a href="#/plants/{{plant.id}}"></a>
</div>

And, in fact question. In html I see data from json, and the controller when accessing the plants I see an empty object?

for (var p in plants) {
  . . .
}

How to get data from the plants in the controller?

Thank you all for your answers.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Cause it is asynchronous call. After $scope.plants = DataPlant.query();, plants remain undefined until data arrives (Well, it is not exactly undefined, you can inspect it in debugger). When data arrives - $scope.plants get resolved and html is updated. To run some code after data arrives, use callbacks:

$scope.plants = DataPlant.query(function(response) {
        console.log($scope.plants);
}, function (response) {
        console.log('Error');
});
share|improve this answer
    
Thanks! It works –  pavel Mar 14 at 19:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.