techwestcoastsfosea
techwestcoastsfosea

Reputation: 778

Ionic - trouble with accessing an object

I have a web service that returns an object called response. It has an object data. When I do the following:

  var myObject = JSON.stringify(response.data);
  console.log("My Results: " + myObject);

[{"id":"1","username":"sam","user_id":"1","status":"1"}]

But I am having trouble accessing these objects in a scope.

for example

$scope.myresponse = response.data;
$scope.myresponse.username = response.data.username

It doesn't work. I even tried $scope.myresponse = response.data[0]; that didnt' work either. Any suggestions?

Upvotes: 0

Views: 50

Answers (2)

techwestcoastsfosea
techwestcoastsfosea

Reputation: 778

Actually the solution turned out be an easy one. Not very clean but it works.

$scope.myData = response.data; $scope.myResults = $scope.myData[0];

After this I was able to access all the elements e.g. id by {{myResults.id}} in my view.

Thank you all for your help.

Upvotes: 0

Ajay
Ajay

Reputation: 4971

Store response return from backend call inside a service layer variable and access that variable from controller to get the required result.

Demo code showing above interaction...

In ServiceLayer.js

var myObject = response["data"];

function getMyObject() {
    return myObject;    
}

In Controller.js

Inject that registered service and access myObject variable.

$scope.myresponse = this.serviceLayer.getMyObject();

use this myResponse variable to access any required information.

Regards

Ajay

Upvotes: 1

Related Questions