Search code examples
javascriptangularjsng-options

Duplicates in ngOptions


I am using AngularJS version 1.4.7 and have simple AngularJS controller which contains array of objects. I would like to display these objects as options in select by ngOptions.

The problem is that every object is duplicate and I don't know why. This duplicate is presented in the select only, the source object looks fine.

angular
  .module('demo', [])
  .controller('DemoCtrl', DemoCtrl);

function DemoCtrl() {
  var vm = this;
  
  vm.demoOptions = [
    {value: 1, label: 'Demo 1'},
    {value: 2, label: 'Demo 2'},
    {value: 3, label: 'Demo 3'}
  ];
  vm.selected = null;;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<div ng-app="demo" ng-controller="DemoCtrl as vm">
  <select ng-options="item as item.label for item in vm.demoOptions track by item.value" ng-model="vm.selected">
    <option value="" selected ng-if="vm.selected === null">-- select --</option>
  </select>
  <p ng-if="vm.selected !== null">Selected item: <code>{{vm.selected}}</code></p>
  <p ng-if="vm.selected === null">No item is selected.</p>
  <pre>vm.demoOptions == {{vm.demoOptions|json}}</pre>
</div>

Is it a bug? How can I remove duplicates without using a filter?

Note: This problem has occurred after update AngularJS from version 1.3.19 to 1.4.7. I read the changelog but it tells only about addition of track by - I added it but with no effect.


Solution

  • It is a known bug for 1.4.x before 1.4.8 you can check issue.

    If you have to use angularjs 1.4.7 version then you can use ng-show instead ng-if

    You can find changelog and error from angularjs github