如何在ng-if和variable中使用过滤器?

时间:2015-07-16 13:27:27

标签: javascript angularjs angularjs-filter angular-ng-if

在此示例中,我在ng-repeat中使用过滤器,但如何在变量和ng-if中使用过滤器,如:

{{languages.length | filter: {available: true}}}

ng-if="languages.length == 0 | filter: {available: true}"

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

3 个答案:

答案 0 :(得分:47)

你能试试吗?

<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>

答案 1 :(得分:6)

只是为了更新以前的答案,不需要过滤三次,在第一个过滤器上创建新变量'filtered':

<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/

答案 2 :(得分:2)

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

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

这对我有用