How to use filter in ng-if and variable?
Asked Answered
C

3

30

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}
];
Corroboration answered 16/7, 2015 at 13:27 Comment(3)
i dont know why do you want to do this , simply you can do <ol> <li ng-if="languages.length" ng-repeat="language in languages | filter: {available: true}">{{language.name}}</li> </ol>Cantlon
I simply want to display how many languages are available, just as I display the number of total languages. I could make a function to do this and do the filtering in JavaScript but I would expect there to be a way to do this in Angular syntax in the HTML code.Corroboration
Sometimes short function in $scope is more readable than spagetti code in html.Schuler
S
59

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>
Searle answered 16/7, 2015 at 13:50 Comment(0)
M
6

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/

Mccurdy answered 16/7, 2015 at 15:6 Comment(0)
O
2
<div ng-if="(answerText|lowercase)=='true'">T</div>

<div ng-if="(answerText|lowercase)=='false'">F</div>

This works for me

Ostrom answered 7/8, 2017 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.