What is easy way to convert object in array Angular JS?

前端 未结 3 1420
失恋的感觉
失恋的感觉 2021-01-05 07:30

My application was built on Angular JS and has a lot AJAX requests on server. For example, in PHP I format output array like as:

$dialog[$us         


        
3条回答
  •  花落未央
    2021-01-05 08:02

    You don't need to convert object to array in order to iterate over it in ng-repeat. You can just use the following syntax:

    {{key}} => {{value}}

    Documentation of ngRepeat.

    Unfortunately, this approach will not work with orderBy filter. To iterate over object properties in specific order, you need to implement your own filter. It may be something like that:

    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;
        };
      }]);
    

    HTML

    {{key}} => {{value}}

    Plunker

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

    However even this approach will work only starting from 1.4.x, since as it is stated in documentation, AngularJS prior to 1.4.x will sort object properties in alphabetic order while iterating over them in ngRepeat.

    In order to make it work in Angular 1.3.x or even 1.2.x you may perform conversion of object to array of objects, each one of which will contain key and value properties. That way you will be able to use it in ngRepeat in combination with filters including orderBy. Here is a code:

    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();
      }]);
    

    HTML

    {{item.key}} => {{item.value}}

    Plunker

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

提交回复
热议问题