2

I'm quite new to angularjs and somehow theres something I can't make a workaround.

Its getting a single value from a json array and then placing it in a scope variable. Lets say just got an array from a php query which looks like this (printed view):

array(
[name]   => John Doe,
[age]    => 29,
[gender] =>male);

And then it is added through this scope variable:

$scope.profile = response.data;

How can I pick a single a value from that array and then place it separate scope variables?

$scope.name; $scope.age; $scope.gender;
9
  • try response.data.name or response.data['name'] and assign it to $scope.name Commented May 29, 2016 at 13:35
  • I tried it, it didn't work. Looks like I need to transfer it to object from json first. Commented May 29, 2016 at 13:40
  • Parse json object in javascript or try to send php data in json_encoded format Commented May 29, 2016 at 13:42
  • use this method for parsing json JSON.parse(response); and store it in variable Commented May 29, 2016 at 13:43
  • I tried this: $scope.profile = JSON.parse(response); and even $scope.profile = JSON.parse(response.data); but its not returning anything. Commented May 29, 2016 at 13:47

2 Answers 2

1

Send your data back from your PHP using json_encode

return json_encode($array);

which will then give you

object {
 name: 'John Doe',
 age: '29',
 gender: 'male'
} 

And you can then access it using:

$scope.profile = response.data;
//
$scope.name   = $scope.profile.name;
$scope.age    = $scope.profile.age;
$scope.gender = $scope.profile.gender;

Example:

var app = angular.module('someApp', [])
  .controller('someCtrl', function ($scope) {
    
    var object = {
      name: 'John Doe',
      age: '29',
      gender: 'male'
    };

    $scope.profile = object;
    
    $scope.name   = $scope.profile.name;
    $scope.age    = $scope.profile.age;
    $scope.gender = $scope.profile.gender;
    
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="someApp" ng-controller="someCtrl">{{name}}, {{age}}, {{gender}}</div>

Sign up to request clarification or add additional context in comments.

Comments

0
$scope.name = response.data.name;
$scope.age = response.data.age;
$scope.gender = response.data.gender;

This should add them to the $scope.

Make sure that the elements are in an object, not JSON string anymore.

Or if you stay with the other one you already have:

$scope.name = $scope.profile.name;
$scope.age = $scope.profile.age;
$scope.gender = $scope.profile.gender;

3 Comments

the elements are still on JSON string. How can I transfer it first?
JSON.parse(stringToParse);
i tried it, but its not working. its nor returning anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.