如何在没有Angular JS的情况下将过滤器添加到<select>?

时间:2017-05-15 11:16:56

标签: javascript angularjs select filter ng-options

我有一个选择声明 &lt; select ng-model =“selectedItem”ng-change =“onChange()”&gt;         &lt; option id =“{{item.toLowerCase()}}”ng-repeat =“someArray中的项目”&gt; {{item}}&lt; / option&gt;     &LT; /选择&GT; 并希望对选项应用过滤器以在下拉列表中显示不同的值。有任何想法吗? 当使用ng-options时很容易(见下文),但现在我似乎无法让它工作。 &LT;选择 ng-options =“item as(item | filterThatIWant)for someArray中的item NG-模型= “selectedItem属性” NG-变化=“的onChange()&GT; &LT; /选择&GT; 基本上我只需要相当于上面的内容。没有ng-options。 谢谢

2 个答案:

答案 0 :(得分:0)

与ng-option

相同
<select ng-model="selectedItem" ng-change="onChange()">
    <option id="{{item.toLowerCase()}}" ng-repeat="item in someArray | filterThatIWant">{{item}}</option>
</select>

答案 1 :(得分:0)

您可以使用ng-repeat选项,

<select ng-model="selectedItem" ng-change="onChange()">
    <option id="{{item.toLowerCase()}}" ng-repeat="item in someArray">{{item | filterThatIWant}}</option>
</select>

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>


<select ng-app="myApp" ng-controller="namesCtrl"ng-model="selectedItem" ng-change="onChange()">
    <option id="{{item.toLowerCase()}}" ng-repeat="item in names">{{item | myFilter}}</option>
</select>


<script>
var app = angular.module('myApp', []);
app.filter('myFilter', function() {
    return function(x) {
        var i, c, txt = "";
        for (i = 0; i < x.length; i++) {
            c = x[i];
            if (i % 2 == 0) {
                c = c.toUpperCase();
            }
            txt += c;
        }
        return txt;
    };
});
app.controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
        ];
});
</script>

<p>This filter, called "myFilter", will uppercase every ODD character.</p>
</body>
</html>

请运行以上代码段

Here is a WORKING DEMO