AngularJS gets the length of a specific element in a JSON array

Hi, I have a JSON array that I am calling from a service. I have some counters that I would like to print the length of the full array and the length of some subelements. I can print the entire length of the array, but I would also like to print the total number of elements that have a progress of "green", "red" and "yellow". Seeing that this is an array of objects, how am I going to get the length of green, red, yellow?

JSON:

[
   {
     name: User1,
     progress: "green"
   },
   {
     name: User2,
     progress: "yellow"
   },
   {
     name: User3,
     progress: "green"
   },
    {
     name: User4,
     progress: "red"
   },
]

I store a service called like this:

$scope.requestDetails = [];
$scope.requestDetails = data;

HTML:

<div class="total">{{requestDetails.length}}</div>
<div class="red"></div>
<div class="yellow"></div>
<div class="green"></div>

Out of curiosity, I tried to print {{requestDetails.progress.length}}, but it was empty, and printing {{requestDetails[0].progress.length}}prints the number of letters of the first value of the progress of the object.

+4
3

angular:

{{requestDetails.lenght}}

{{(requestDetails | filter: {progress: 'red'}).length}}

:

:

  $scope.colorFilter = function(color) {
    return function (obj) {
      return obj.progress === color;
    };
  };

{{(requestDetails | filter: colorFilter('red')).length}}

: angular 1.3 , $watcher, $digest, 2 - .

Plunker: http://plnkr.co/edit/zgzSqeMVnCQbpDitrSI3?p=preview

+4

, :

$scope.itemData = {};
for (var i = 0; i < $scope.requestDetails.length; ++i) {
  var detail = $scope.requestDetails[i];
  if ($scope.itemData[detail.progress] === undefined) {
    $scope.itemData[detail.progress] = 0;
  }
  $scope.itemData[detail.progress]++;
}

:

<div class="red">{{ itemData.red }}</div>
<div class="green">{{ itemData.green }}</div>
0

, , ?

, .

HTML

<div>{{requestDetails.length}}</div>
<div class="red">{{(requestDetails | filter: {progress: 'red'}).length}}</div>
<div class="green">{{(requestDetails | filter: {progress: 'green'}).length}}</div>

angular. , docs.

0

Source: https://habr.com/ru/post/1606292/


All Articles