Aziz Alfoudari
Aziz Alfoudari

Reputation: 5263

AngularJS - Access JSON object associated to a model

I have a service that returns JSON, assume this is the response:

{
    "model": 48870,
    "id": 20
}

I can do this:

$scope.response = Service.get();

And it will assign the JSON response to $scope.response. The issue here is I cannot directly access model or id via $scope.response.model or $scope.response.id, respectively. My workaround for this situation is to define a function in the service's success callback and fetch model or id from data. But this is not very practical considering $scope.response contains the entire JSON object and should in theory (and the sake of clean code) let me access its children.

Two questions here:

  1. Is it a limitation of AngularJS representation of models?
  2. How can I point to children (even grandchildren) without having to define a success callback for each call?

Upvotes: 3

Views: 7218

Answers (2)

vsp
vsp

Reputation: 916

Once the asynchronous HTTP call returns, it is safe to access response's properties directly.

See this short example

app.controller('MainCtrl', function($scope, $resource) {
  $scope.data = $resource('data.json').get(function() {
    $scope.loaded = true;
    //now it's safe to access $scope.data's properties:
    $scope.data.foo = $scope.data.id + ':' + $scope.data.model;
  });
});

UI bindings will work automatically.

Upvotes: 1

mstreffo
mstreffo

Reputation: 805

I think what you are looking for is described here:

http://docs.angularjs.org/tutorial/step_05

Upvotes: 0

Related Questions