J_tt
J_tt

Reputation: 13

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" }

Upvotes: 1

Views: 55

Answers (3)

Marcos
Marcos

Reputation: 4643

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.

Upvotes: 1

satyendra kumar
satyendra kumar

Reputation: 759

check if your response is array, if array then you need to do something like this, $scope.userData = response[0].userData.

If still not getting solution please share or response format.Entire response structure.

Upvotes: 0

Patrick Vogt
Patrick Vogt

Reputation: 916

Maybe you have to declare the $scope.userData variable outside of the then-function

Upvotes: 1

Related Questions