J_tt J_tt - 3 months ago 10
JSON Question

Outputting JSON Data in Angular Expressions

My PHP script returns this JSON data:

{
"userData": {
"userName": "knows_nothing",
"userFullName": "Jon Snow",
"userMoney": "124.01"
}
}


How can I access the variables (userName etc) in my webpage?

eg:

JS



var app = angular.module('dashboard', []);
app.controller('userDataCtrl', function($scope, $http) {
data = "{query:'userData'}"
$.post("api/mysql.php", {query:'userData'})
.then(function (response) {$scope.userData = response.userData;});
});


HTML



<div ng-app="dashboard">
<div ng-controller="userDataCtrl">
<h1> Username: {{ userData.userName }} </h1>
<p> Balance: {{ userData.balance }} </p>
</div>
</div>


This has been driving me insane for hours :(

This is what it outputs when I `console.log(response.userData)

Object { userName: "knows_nothing", userFullName: "Jon Snow", userMoney: "124.01" }

Answer

According to $http documentation you should read the response from response.data. So, in your case:

...
.then(function (response) {$scope.userData = response.data.userData;});

should do the trick.