In this example, I use filter in the ng-repeat
, but how do I use it in a variable and ng-if
, something like:
{{languages.length | filter: {available: true}}}
and
ng-if="languages.length == 0 | filter: {available: true}"
See Fiddle.
HTML
<div ng-controller="mainController"> <div>There are {{languages.length}} languages in total.</div> <div>??? There are {{languages.length}} languages available.</div> <div ng-if="languages.length == 0">??? Sorry, there are no languages available.</div> <ol> <li ng-repeat="language in languages | filter: {available: true}">{{language.name}}</li> </ol> </div>
AngularJS
$scope.languages = [ {id:1, name:"German", available: false}, {id:2, name:"English", available: true}, {id:3, name:"French", available: false}, {id:4, name:"Italian", available: true}, {id:5, name:"Spanish", available: false} ];
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.
AngularJS ng-if DirectiveThe ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
Can you try this?
<div ng-controller="mainController"> <div>There are {{languages.length}} languages in total.</div> <div>There are {{(languages|filter:{available:true}).length}} languages available.</div> <div ng-if="(languages|filter:{available:true}).length == 0">Sorry, there are no languages available.</div> <ol> <li ng-repeat="language in languages | filter: {available: true}">{{language.name}}</li> </ol> </div>
Just to update previous answer, no need to filter three times, create new variable 'filtered' on first filter:
<div ng-controller="mainController"> <div>There are {{languages.length}} languages in total.</div> <div>There are {{(filtered = (languages|filter:{available:true})).length}} languages available.</div> <div ng-if="filtered.length == 0">Sorry, there are no languages available.</div> <ol> <li ng-repeat="language in filtered">{{language.name}}</li> </ol> filtered=[{{filtered}}] </div>
http://jsfiddle.net/to7z06ma/18/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With