Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Access JSON object associated to a model

Tags:

angularjs

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?
like image 925
Aziz Alfoudari Avatar asked Feb 05 '26 13:02

Aziz Alfoudari


1 Answers

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.

like image 157
vsp Avatar answered Feb 08 '26 03:02

vsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!