Reputation: 381
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
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.
});
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
Reputation: 5711
$scope.data = QA.get();
console.log(data);
or in your template:
{{data | json}}
This will give you a hint
Upvotes: 0