在数组Angular JS中转换对象的简单方法是什么?

vav*_*ved 7 javascript angularjs

我的应用程序是基于Angular JS构建的,并且在服务器上有很多AJAX请求.例如,在PHP中,我将输出数组格式化为:

$dialog[$userId] = array(
   'time' => $key,
   'message' => $message['message'],
   'name_user'  => $info['name']
);

echo json_encode($dialog); die();
Run Code Online (Sandbox Code Playgroud)

但是在Angular JS中,我得到的不是数组而是对象:

549:Objectid_user:"549"消息:"你好"name_user:"Ali Akhmedov"时间:1432070505

问题,如果使用ng-repeat然后不能对对象进行排序.为什么在PHP中我设置数组但在客户端获取对象?

将对象转换为数组的简单方法是什么?因为我在AJAX页面上有很多对象.

Vad*_*dim 11

您不需要将对象转换为数组以便迭代它ng-repeat.您可以使用以下语法:

<div ng-repeat="(key, value) in items">{{key}} => {{value}}</div>
Run Code Online (Sandbox Code Playgroud)

文档ngRepeat.

不幸的是,这种方法不适用于orderBy过滤器.要按特定顺序迭代对象属性,您需要实现自己的过滤器.它可能是这样的:

JavaScript的

angular.module('app', []).
  filter('orderByKey', ['$filter', function($filter) {
    return function(items, field, reverse) {
      var keys = $filter('orderBy')(Object.keys(items), field, reverse),
          obj = {};
      keys.forEach(function(key) {
        obj[key] = items[key];
      });
      return obj;
    };
  }]);
Run Code Online (Sandbox Code Playgroud)

HTML

<div ng-repeat="(key, value) in items | orderByKey:'-'">{{key}} => {{value}}</div>
Run Code Online (Sandbox Code Playgroud)

Plunker

http://plnkr.co/edit/DJo0Y6GaOzSuoi202Hkj?p=preview

然而,即使这种方法仅起作用1.4.x,因为正如文档中所述,AngularJS之前1.4.x将按字母顺序对对象属性进行排序,同时迭代它们ngRepeat.

为了使它在Angular中工作,1.3.x甚至1.2.x你可以执行对象到对象数组的转换,每个对象都包含keyvalue属性.这样你就可以将它ngRepeat与过滤器结合使用了orderBy.这是一个代码:

JavaScript的

angular.module('app', []).
  factory('srv', ['$http', function($http) {
    var items = [],
        loaded = false;
    return {
      getItems: function() {
        if(!loaded) { // Lazy loading
          $http.get('data.json').success(function(data) { // {key1: 'val1', key2: 'val2'}
            Object.keys(data).forEach(function(key) {
              items.push({key: key, value: data[key]});
            });
          });
          loaded = true;
        }
        return items; // [{key: 'key1', value:'val1'}, {key:'key2', value: 'val2'}]
      }
    };
  }]).
  controller('ctrl', ['$scope', 'srv', function($scope, srv) {
    $scope.items = srv.getItems();
  }]);
Run Code Online (Sandbox Code Playgroud)

HTML

<div ng-repeat="item in items | orderBy:'-key'">{{item.key}} => {{item.value}}</div>
Run Code Online (Sandbox Code Playgroud)

Plunker

http://plnkr.co/edit/UXmlm1GKYRZzrOV5pMYT?p=preview


Raz*_* B. 5

假设你有一个像这样的对象:

$scope.myObj = {type:"Fiat", model:500, color:"white"};
Run Code Online (Sandbox Code Playgroud)

然后,在你的角度Controller你可以做类似的事情:

$scope.array = [];
angular.forEach($scope.myObj, function(element) {
  $scope.array.push(element);
});
Run Code Online (Sandbox Code Playgroud)

然后在你的 HTML

<div ng-repeat="obj in array">{{obj}}</div>
Run Code Online (Sandbox Code Playgroud)

这是一个演示插件