Search code examples
angularjssortingangularjs-orderby

Select dropdown not generated via ng-repeat and ng-options


The two dropdowns below doesnt generate an array of years. I also need the years to be sorted from earliest to latest but the orderBy filter isnt working.

 <select title="- Select a period -" class="period " id="reportingPeriods">
        <option ng-repeat="reportingPeriod for reportingPeriod in reportingPeriods">{{reportingPeriod}}</option>
      </select>
      <br />
      <select title="- Select a period -" class="period selectpicker" id="" 
      ng-options="reportingPeriod for reportingPeriod in reportingPeriods | orderBy: '-reportingPeriod' ">
      </select>

Here is my javascript

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    console.clear();
    $scope.data = {
     repeatSelect: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
    };

    $scope.reportingPeriods = [1999, 2011, 2000, 1988, 1995, 2014];
 }]);
})(window.angular);

Here is my plunkr


Solution

  • You are using the wrong syntax for the ng-options and ng-repeat in the select options. Fixed here - http://plnkr.co/edit/oPI9kvQFuYJmrEwBDnWv?p=preview

    Also you need to assign your ng-models to the select for them to work (as mentioned in the comments above by @AvijitGupta)

    <select ng-model="period" title="- Select a period -" class="period " id="reportingPeriods">
        <option ng-repeat="reportingPeriod in reportingPeriods">{{reportingPeriod}}</option>
      </select>
      <br />
      <select ng-model="preiod" title="- Select a period -" class="period selectpicker" id="" 
      ng-options="reportingPeriod for reportingPeriod in reportingPeriods | orderBy: '-' ">
      </select>