Using $index with the AngularJS 'ng-options' directive?

后端 未结 5 1330
暖寄归人
暖寄归人 2020-12-01 01:37

Say that I bind an array to a select tag using the following:


                        
    
提交评论

  • 2020-12-01 01:47

    Since arrays are very similar to objects in JavaScript, you can use the syntax for "object data sources". The trick is in the brackets in the ng-options part:

    var choices = [
      'One',
      'Two',
      'Three'
    ];
    

    In the template:

    <select
      ng-model="model.choice"
      ng-options="idx as choice for (idx, choice) in choices">
    </select>
    

    In the end, model.choice will have the value 0, 1, or 2. When it's 0, you will see One; 1 will display Two, etc. But in the model, you will see the index value only.

    I adapted this information from "Mastering Web Application Development with AngularJS" by PACKT Publishing, and verified at the Angular reference documentation for select.

    0 讨论(0)
  • 2020-12-01 01:50

    Don't use $index inside select tags. Use $index inside the option tags if you want to use the array indexes as either values or options.

    <option ng-repeat="user in users" value="{{user.username}}">{{$index+1}}</option>
    

    If you want to use inside values just put it in the value attribute as binding expression like

    <option ng-repeat="user in users" value="{{$index+1}}">{{user.username}}</option>
    

    and my controller code be like:

    var users = ['username':'bairavan', 'username':'testuser'];
    
    0 讨论(0)
  • 2020-12-01 02:00

    Since you can't use $index but you can try indexOf.

    HTML

    <div ng-app ng-controller="MyCtrl">
        <select 
              ng-model="selectedItem"
              ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
        selectedItem: {{selectedItem}}
    </div>
    

    Controller

    function MyCtrl($scope) {
        $scope.values = ["Value1","Value2"];
        $scope.selectedItem = 0;
    }
    

    Demo Fiddle

    Comment:

    Array.prototype.indexOf is not supported in IE7 (8)

    0 讨论(0)
  • 2020-12-01 02:04

    $index is defined for ng-repeat, not select. I think this explains the undefined. (So, no, this shouldn't work.)

    Angular supports binding on the entire object. The documentation could be worded better to indicate this, but it does hint at it: "ngOptions ... should be used instead of ngRepeat when you want the select model to be bound to a non-string value."

    0 讨论(0)
  • 提交回复
    热议问题