javascript Angularjs从数组中获取单个值

时间:2016-05-29 13:26:27

标签: javascript php arrays angularjs scope

我对angularjs很新,不知何故,我无法解决这个问题。

从json数组中获取单个值,然后将其放入范围变量中。让我们说只是从一个php查询得到一个数组看起来像这样(打印视图):

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

然后通过此范围变量添加它:

$scope.profile = response.data;

如何从该数组中选择一个值,然后将其放在单独的范围变量中?

$scope.name; $scope.age; $scope.gender;

2 个答案:

答案 0 :(得分:1)

使用json_encode

从PHP发回数据
return json_encode($array);

然后会给你

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

然后您可以使用以下方式访问它:

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

示例:



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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

这应该将它们添加到$scope

确保元素位于对象中,而不再是JSON字符串。

或者,如果你和另一个人在一起,那么:

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