【问题标题】:How to add filter to <select> without <ng-options> in Angular JS?如何在 Angular JS 中不带 <ng-options> 的情况下向 <select> 添加过滤器?
【发布时间】:2017-05-15 11:16:56
【问题描述】:

我有一个选择语句

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

并希望对选项应用过滤器以在下拉列表中显示不同的值。有任何想法吗?

使用 ng-options 很简单(见下文),但现在我似乎无法正常工作。

<select
ng-options="item as (item | filterThatIWant) for item in someArray
ng-model="selectedItem"
ng-change="onChange()>
</select>

基本上我只需要上面的等价物。没有 ng 选项。

谢谢

【问题讨论】:

    标签: javascript angularjs select filter ng-options


    【解决方案1】:

    和ng-option一样

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

    【讨论】:

      【解决方案2】:

      您可以使用 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>

      请运行上面的 sn-p

      Here is a WORKING DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-27
        • 2011-11-03
        • 1970-01-01
        • 1970-01-01
        • 2014-02-19
        • 2015-08-01
        • 2016-01-22
        • 1970-01-01
        相关资源
        最近更新 更多