How to use filter in ng-if and variable?

无人久伴 提交于 2020-01-22 08:23:09

问题


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}
];

回答1:


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>



回答2:


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/




回答3:


<div ng-if="(answerText|lowercase)=='true'">T</div>

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

This works for me



来源:https://stackoverflow.com/questions/31455567/how-to-use-filter-in-ng-if-and-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!