Piddien
Piddien

Reputation: 1446

AngularJS - showing an item only if none of the booleans in a collection are true

I would like to show the button in the code only if none of the aspects in $scope.aspects are true.

<aspect-form ng-repeat="aspect in aspects | filter:{active: true}">
</aspect-form>
<a class="btn btn-primary btn-lg" role="button">Save</a>

How would I do this?

Upvotes: 0

Views: 42

Answers (4)

Constantinos
Constantinos

Reputation: 1208

In situations like these I like to use the array.every() and array.some() functions:

<a class="btn btn-primary btn-lg" role="button" ng-if="allAspectsFalse()">Save</a>

$scope.allAspectsFalse = function() {
  return $scope.aspects.every(function(aspect) {
    return !aspect.active;
  });
}

Upvotes: 1

jdmcnair
jdmcnair

Reputation: 1315

You can do it without binding to a function on the scope like this:

<a class="btn btn-primary btn-lg" 
  ng-if="(aspects | filter:{active: true}).length === 0">Save</a>

Upvotes: 3

Piddien
Piddien

Reputation: 1446

I also found a solution. Mine is using ng-show instead but is practically the same. I will show the whole solution.

<a class="btn btn-primary btn-lg" role="button" ng-show="someAspectShowing()">Save</a>

and in the controller I have defined the function:

$scope.someAspectShowing = function() {
  for(index=0; index < $scope.aspects.length; ++index) {
    if($scope.aspects[index].active === true) {
      return true;
    }
  }
  return false;
  };

Upvotes: 0

M.K. Safi
M.K. Safi

Reputation: 7019

You can use ng-if in the a element, and give it a function that evaluates to true only when all of the aspects in $scope.aspects are false.

<a class="btn btn-primary btn-lg" ng-if="allAspectsAreFalse()">Save</a>

Upvotes: 0

Related Questions