AngularJS从工厂宣传数据

时间:2017-01-24 14:07:50

标签: javascript angularjs

我正在处理恼人的问题。我有一个角度工厂,它拥有一系列虚拟数据。我正在将这些数据从工厂扫描到我的控制器,并在我的视图中使用ng-repeat显示,它工作得很好。但我的问题是我应该如何以及在哪里编写一些代码来获取有关数组中数据的更多信息,例如,如果数组看起来像这样:

[
...
{"id":186,"imie":"Bérangère","nazwisko":"West","plec":"Female","adres":"4 Lindbergh Park","zawod":"solution","narodziny":"1927-01-31"},
{"id":187,"imie":"Marylène","nazwisko":"Cooper","plec":"Male","adres":"7 Summit Avenue","zawod":"Profound","narodziny":"1931-09-24"},
{"id":188,"imie":"Gösta","nazwisko":"Nelson","plec":"Female","adres":"5 Corscot Terrace","zawod":"context-sensitive","narodziny":"1954-11-03"},
{"id":189,"imie":"Clélia","nazwisko":"Moore","plec":"Male","adres":"500 Daystar Plaza","zawod":"task-force","narodziny":"1997-01-14"}
...
]

我想显示"plec":"Female"的用户总数。

我应该编写一个JavaScript for循环来检查我的数据,还是有一个“Angular方式”来处理它?<​​/ p>

3 个答案:

答案 0 :(得分:1)

在Angular中,最好在您的工厂中进行

(function () {
        'use strict';

        angular
            .module('app')
            .factory('MyFactory', MyFactory);

        MyFactory.$inject = ['$http'];

        /* @ngInject */
        function MyFactory($http) {
            var service = {
                dummyUserData: [],
                getUserCountsWhere: getUserCountsWhere
            };

            return service;

            ////////////////

            function getUserCountsWhere(key, value) {
                // key is plec , value is "Female"
                return service.dummyUserData.filter(function(user){
                    return user[key] == value;
                }).length;
            }

        }
    })();

答案 1 :(得分:0)

在您的工厂(或您可以访问此对象的任何地方),您可以编写一个计算并返回数组中女性数量的函数:

var data = [ ... ];

var countFemales = function() {
    var counter = 0;
    for(var i = 0; i < data.length; i++) {
        if(data[i].plec == "Female") counter++;
    }
    return counter;
}

答案 2 :(得分:0)

试试这个,使用lodash'reduce,看起来有点整洁:

function countingMethod() {
  return _.reduce(data, (key, val, acc) => {
    if (data[key]['plec'] === 'Female') {
      acc++;
    }
    return acc;
  }, 0);
}

或非lodash版本:

function countingMethod() {
  return data.reduce((key, val, acc) => {
    if (data[key]['plec'] === 'Female') {
      acc++;
    }
    return acc;
  }, 0);
}