Eimantas
Eimantas

Reputation: 429

Angular.js render data in controller

I have a rather simple question. I have a simple controller and its $scope.coords = []; renders JSON in HTML:

[24.43359375, 54.6611237221]
[25.2905273438, 54.6738309659]
[25.3344726562, 54.6102549816]
[25.2685546875, 54.6801830971]
[25.2960205078, 54.6611237221] 

How can I render that JSON not in html, but in my controller itself ? The code looks like that. Please see the comment in code:

propertyModule.controller('propertyController', ['$scope', 'Property', function ($scope, Property) {

        // Query returns an array of objects, MyModel.objects.all() by default
        $scope.properties = Property.query();

        // Getting a single object
        $scope.property = Property.get({pk: 1});

        $scope.coords  = [];

        $scope.properties = Property.query({}, function(data){

        console.log(data);

        angular.forEach(data , function(value){

            $scope.coords.push(value.coordinates);

        });

        });

        $scope.positions =  //$Resource('realestate.property').items();

        [

        [54.6833, 25.2833], [54.67833, 25.3033] // those coordinates are hardcoded now, I want them to be rendered here by $scope.coords


        ];


    }]);

Upvotes: 0

Views: 226

Answers (1)

Goodzilla
Goodzilla

Reputation: 1483

First off, you're showing us a bunch of arrays, not a JSON document. But since your code seems to be working, I'll assume you do have a valid JSON to work with.

You need to consider the fact that you are making an asynchronous request here :

$scope.properties = Property.query({}, function(data) {

    console.log(data);

    angular.forEach(data , function(value){
        $scope.coords.push(value.coordinates);
    });

});

This means you won't be able to fetch data from $scope.coords before anything has arrived.

There are several ways to solve that :

  • You could simply fetch data while you're still in the loop :

    angular.forEach(data , function(value) {
        $scope.coords.push(value.coordinates);
        if('your condition') {
            $scope.positions.push(value.coordinates);
        }    
    });
    
  • You could use a promise, see the angular doc.

  • Or you could watch over $scope.coords with $scope.$watch.

Upvotes: 1

Related Questions