angularJS表达式中的自定义过滤器

时间:2014-03-11 11:36:06

标签: angularjs angularjs-directive angularjs-filter

我想使用AngularJS在.tpl.html文件中自定义过滤器。

以下是我的情况,

控制器:

$scope.selectedFruits = [{'name': 'mango', 'color': 'yellow'}];

$scope.favouriteFruits = [{'name': 'cherry', 'color': 'red'}, 
                          {'name': 'papaya', 'color': 'yellow'}];

$scope.fruits = [{'name': 'apple', 'color': 'red'}, 
                 {'name': 'mango', 'color': 'yellow'}, 
                 {'name': 'guava', 'color': 'green'},
                 {'name': 'grape', 'color': 'black'},
                 {'name': 'cherry', 'color': 'red'}, 
                 {'name': 'papaya', 'color': 'yellow'},
                 {'name': 'orange', 'color': 'orange'}];

模板

<select name="fruit" class="form-control" 
        ng-model="model.selectedFruits" 
        ng-options="fruit as fruit.name 
                    for fruit in filteredFruits)"/>
</select>

filterFruits应该像这样过滤:

filteredFruits = (fruits not in (selectedFruits and favouriteFruits)) 

我如何实现上述情况?

1 个答案:

答案 0 :(得分:0)

您可以使用angular's built in filter filter

来自文档:

  

$filter('filter')(array, expression, comparator)

expression可以是一个函数,为应包含的项返回true,因此在您的控制器中:

$scope.filterFunction = (fruit)->
  (fruit not in (selectedFruits and favouriteFruits))

然后你的模板:

<select name="fruit" 
        class="form-control" 
        ng-model="model.selectedFruits" 
        ng-options="fruit as fruit.name 
                    for fruit in fruits | filter:filterFunction)"/>

Plunker demo here