Bones and Teeth
Bones and Teeth

Reputation: 381

How can I access value in json in AngularJS

I am using nodeJS so the server will send the following json object to controller by doing:

data = {
    "question": "theQuestion",
    "answer": "theAnswer"
};
res.json(data);

Then in the controller, I want to manipulate the variable like:

data = QA.get();
$scope.q = data[question] + "Some additional info here";

QA is the service defined as:

angular.module('questionServices', ['ngResource'])
.factory('QA', function  ($resource) {
    return $resource('/qa');
});

However, the error message always tells me that data[question] is undefined. What is the right way to access the value? I have tried data.question. It doesn't work either.

I know I can simply show the json values by using ng-repeat in html but I want to be more flexible managing the values.

Upvotes: 0

Views: 684

Answers (2)

Tyler.z.yang
Tyler.z.yang

Reputation: 2450

Seems you QA function you use $http or $resource to get the ajax response.

If you return $http.get/$http.post in you QA service, you can use this code to handle the json response:

QA.get().success(function(data){
    console.log(data);
    console.log(data.answer);
}).error(functoin(data){
    //handle error here.
});

If you use $resource in your QA service, then you can use this code to handle that:

QA.get().$promise.then(function(data){
     console.log(data);
     console.log(data.answer);
}).then(function(error){
     //handler error here.
});

Here is $http document.

Here is $resource document.

P.S you need to understand in ajax, javascript handle the request in async. That means when exec these code:

$scope.data = QA.get()
console.log($scope.data);  // QA.get()  send a http request. Now data is still promise object.

you cannot get this response immediately. So if you try to log the data, or use console.log(data.answer) to get data.answer. you will get undefined

However in you html view. You can get the data with {{data|json}} . This is because angular will $watch your data. And once data($resource promise object) is change(means http request is finished), Angular will render your view automatically.

That's why in your view you can get data.answer. But in your controller, you cannot.

Upvotes: 1

oori
oori

Reputation: 5711

$scope.data = QA.get();
console.log(data);

or in your template:

{{data | json}}

This will give you a hint

Upvotes: 0

Related Questions