Alvin Alvin - 6 months ago 59
AngularJS Question

javascript Angularjs get single value from array

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;

Answer

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>