0

This example seems simple enough, I just can't seem to figure out why it is not working (I don't want to use ng-options because that doesn't work with select2, a plugin I want to use once I get this figured out):

HTML:

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        selectedNumber: {{selectedNumber}}
        <select ng-model="selectedNumber">
            <option ng-repeat="number in numbers" value="{{number}}">{{number}}</option>
        </select> 
        <div ng-repeat="number in numbers">
            {{number}}
        </div>
    </div>
</div>

AngularJS:

var app = angular.module('myApp', []);

app.controller('MyCtrl', function($scope) {
    $scope.numbers = [1, 2];
    $scope.selectedNumber = 2;
});

When inspect the element it looks like this:

<select ng-model="selectedNumber" class="ng-pristine ng-valid">
    <option value="? number:2 ?"></option>
            <!-- ngRepeat: number in numbers -->
    <option ng-repeat="number in numbers" value="1" class="ng-scope ng-binding">1</option>
    <option ng-repeat="number in numbers" value="2" class="ng-scope ng-binding">2</option>
</select>

I am guessing the extra "<option value="? number:2 ?"></option>" is causing this issue but I am not sure how to get rid of it. I also created a jsfiddle of this in action.

testing123
  • 11,367
  • 10
  • 47
  • 61

1 Answers1

1

The reason you see that is because your select is bound to an item that is not contained in its options. Although you are adding options via a ng-repeat I suspect that the directive won't work and is not designed to work this way:

Here is a reference for why that extra value is coming up. AngularJS - extra blank option added using ng-repeat in select tag

I think you have two options: 1. Write your own directive 2. Use the built in ng-options and try to make it work with your plugin

Here is a reference: https://github.com/angular/angular.js/issues/639 and a fiddle from that issue: http://jsfiddle.net/GTynf/3/

Those will probably point you in the right direction for a solution.

Community
  • 1
  • 1
lucuma
  • 18,247
  • 4
  • 66
  • 91