Saturday 15 June 2013

javascript - How can I access value in json in AngularJS -



javascript - How can I access value in json in AngularJS -

i using nodejs server send next json object controller doing:

data = { "question": "thequestion", "answer": "theanswer" }; res.json(data);

then in controller, want manipulate variable like:

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

qa service defined as:

angular.module('questionservices', ['ngresource']) .factory('qa', function ($resource) { homecoming $resource('/qa'); });

however, error message tells me data[question] undefined. right way access value? have tried data.question. doesn't work either.

i know can show json values using ng-repeat in html want more flexible managing values.

seems qa function utilize $http or $resource ajax response.

if homecoming $http.get/$http.post in qa service, can utilize code handle json response:

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

if utilize $resource in qa service, can utilize code handle that:

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

here $http document.

here $resource document.

p.s need understand in ajax, javascript handle request in async. means when exec these code:

$scope.data = qa.get() console.log($scope.data); // qa.get() send http request. info still promise object.

you cannot response immediately. if seek log data, or utilize console.log(data.answer) data.answer. undefined

however in html view. can info {{data|json}} . because angular $watch data. , 1 time data($resource promise object) change(means http request finished), angular render view automatically.

that's why in view can data.answer. in controller, cannot.

javascript json angularjs node.js

No comments:

Post a Comment