KeizerBridge
KeizerBridge

Reputation: 2757

How to display ng-repeat elements only if user uses filters

I would know how to display my elements only if a user uses some filter.

For example:

$scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}];

<input type="text" ng-model="searchText" />
<div ng-repeat="element in elements | filter:searchText">
      <p>{{ element.name }}</p>
</div>

Here I don't want to display the filtered list if users haven't write into the input type text tag. Or the same with input type checkbox, radio, select tag...

What I could do is to use ng-show directive

<div ng-repeat="element in elements | filter:searchText" ng-show="searchText.length > 0">
      <p>{{ element.name }}</p>
</div>

But it does not seem legit.

Any better idea ? or obviously, a native solution.

Thank you in advance.

Upvotes: 0

Views: 100

Answers (2)

sagar43
sagar43

Reputation: 3464

Please check this

$scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}];

<input type="text" ng-model="searchText.name" />
<div ng-repeat="element in elements | filter:searchText">
      <p>{{ element.name }}</p>
</div>

Hope this works.

Upvotes: 2

joey
joey

Reputation: 466

You can use a ng-if that way the code doesn't run until the condition is met.

<div ng-repeat="element in elements | filter:searchText" ng-if="searchText.length > 0">
      <p>{{ element.name }}</p>
</div>

Upvotes: 1

Related Questions