首页 文章

当选择下拉列表时,在Angular中有多个字段

提问于
浏览
2

如何使用select元素按多个字段对数组进行排序?

<select ng-model="selectedOrder">
    <option value='id'>id</option>
    <option value='-id'>-id</option>
    <option value='country'>country</option>
    <option value='address'>address</option>
    <option value='["country","-id"]'>country, -id</option>
    <option value='["-country","address"]'>-country, address</option>        
  </select>

<ul>
  <li ng-repeat="detail in details | filter:{country: countryFilter} | orderBy:selectedOrder">{{ detail }}</li>    
</ul>

如果我在控制器中设置订单选项,一切都很好:
$scope.selectedOrder = ["country", "-id"];

如果选择选项“country,-id”或“-country,address”,则不会进行排序 .

这里有完整的例子http://plnkr.co/edit/w968MMN3qT9AB4XXRosV?p=preview

1 回答

  • 1

    在控制器中指定不同的选项,它将以这种方式顺利运行 . 我不认为 optionvalue 属性可以包含任何类型的对象 .

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
    
    
      $scope.options = [{
        label: "id",
        value: "id"
      }, {
        label: "-id",
        value: "-id"
      }, {
        label: "country",
        value: "country"
      }, {
        label: "address",
        value: "address"
      }, {
        label: "country, -id",
        value: ["country", "-id"]
      }, {
        label: "-country, address",
        value: ["-country", "address"]
      }];
    
    
      // all countries
      $scope.details = [{
        id: 1,
        country: 'Finland',
        address: 'Mainstreet 2'
      }, {
        id: 2,
        country: 'Mexico',
        address: 'Some address 1'
      }, {
        id: 3,
        country: 'Canada',
        address: 'Snowroad 45'
      }, {
        id: 4,
        country: 'Finland',
        address: 'Rainbow 12'
      }, {
        id: 5,
        country: 'Canada',
        address: 'Beverly 15'
      }, {
        id: 6,
        country: 'Mexico',
        address: 'Some address 3'
      }];
    });
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <!DOCTYPE html>
    <html ng-app="plunker">
    
    <head>
      <meta charset="utf-8" />
      <title>AngularJS Plunker</title>
      <script>
        document.write('<base href="' + document.location + '" />');
      </script>
      <link href="style.css" rel="stylesheet" />
      <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script>
      <script src="app.js"></script>
    </head>
    
    <body ng-controller="MainCtrl">
      <div>
        <label>Country filter</label>
        <input type="text" ng-model="countryFilter" />
    
        <label>Order by</label>
        <select ng-model="selectedOrder" ng-options="option.label for option in options">
    
        </select>
      </div>
      <ul>
        <li ng-repeat="detail in details | filter:{country: countryFilter} | orderBy:selectedOrder.value">{{ detail }}</li>
      </ul>
    </body>
    
    </html>
    

相关问题