2

I have an array that always returns 20 items. However, if fewer than 20 items are returned, a " " is returned rather than reducing the number in the array.

For example, myArray with 20 items (only 15 values).

$scope.myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", " ", " ", " ", " ", " "]

I want to perform an ng-show/hide/if on some elements depending on the number of populated in the items in myArray.

Originally I tried:

<div ng-show="myArray.length > 10">
    Show if more than 10 items
</div>

<div ng-show="myArray.length > 15">
    Show if more than 15 items
</div>

<div ng-show="myArray.length > 19">
    Show if more than 19 items
</div>

Naturally, all of the above will show as there are always 20 items returned.

Can I achieve this with an ng-show/hide/if and without having to write additional JS in my controller?

hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
Oam Psy
  • 8,555
  • 32
  • 93
  • 157

2 Answers2

2

Just filter out blank items:

var outBlanks = Boolean;

$scope.nonBlanksCount = $scope.myArray.filter(outBlanks).length;

<div ng-show="nonBlanksCount > 10">
    Show if more than 10 items
</div>

I just read that you did not want to add any logic to your controller. In this case, you could write a custom filter (e.g. filterBlanks) which does the same thing as above and do:

<div ng-show="(myArray | filterBlanks).length > 10">
    Show if more than 10 items
</div>

However in this case, the filter would be executed multiple times, which is not very efficient.

plalx
  • 42,889
  • 6
  • 74
  • 90
0

Would it work for you if you simply augment your array like this?

$scope.myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, "", "", "", ""].filter(Boolean);
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
  • 1
    Since you stole my idea for your answer, I stole a part of yours ;) Using `Boolean` is definitely more elegant. – plalx Oct 10 '14 at 14:38
  • Oh ofcourse, I just tried to improve yours as he wanted to write little or no js on the scope but native functions cant be used in bindings like that so he has to. so as pretty much the only solution I tried to make yours shorter – makeitmorehuman Oct 10 '14 at 14:46