简体   繁体   中英

AngularJS couting the data from factory

I am dealing with annoying problem. I have a angular factory that holds an array of dummy data. And I am grabing this data from factory to my controller and displaying in my view using ng-repeat and it works just fine. But my question is how and where I should write some code to get more information about my data in array, For example If array looks like this:

[
...
{"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"}
...
]

I want to display a total count of users with "plec":"Female" .

Should I write a JavaScript for loop to check my data, or there is an "Angular way" to deal with it?

In Angular, it is best practice to do it in your factory

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

        }
    })();

In your factory (or wherever you can access this object) , you can write a function that counts and returns the number of females in your array:

var data = [ ... ];

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

Try this, using lodash' reduce, which seems a little neater:

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

Or the non-lodash version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM