Why can't I use bi-directional model binding array index in AngularJs?

I'm trying to do what seems so simple: I have an array of string values ​​that I want to bind to select

option

and bind the index of the selected value to a variable. But using ng-options

and regular options

with ng-repeat

doesn't seem to work completely. The latter works as soon as you start fetching values, but does not bind to the value set on page load.

Here the Codepen illustrates the problem. http://codepen.io/modo_lv/pen/xGYQjM (Click View Compiled to see pure HTML and JavaScript). Note that both dropdowns are initially empty, although the value they are bound to is already set. And selecting anything in the first dropdown causes the value to be overridden.

+3


source to share


2 answers


You can link it because $ index is not defined for ngOptions

, it is just a ngRepeat

thing. If you want to know the index of a parameter, you can calculate it using the Array.prototype.indexOf method :

<select ng-model="testModel" 
        ng-options="labels.indexOf(label) as label for label in labels">
</select>

      



Demo: http://codepen.io/anon/pen/MwBXBx

0


source


I have an array of string values ​​that I want to bind to select options and bind the index of the selected value to a variable ...

... neither with ng-options nor with normal options with ng-repeat seems to work completely.

ng-options doesn't work because you are trying to use with it $index

(which only works with ng-repeat

). for your code to work with the ng option, you need to replace

ng-options="$index as label for label in labels"

      

from

ng-options="labels.indexOf(label) as label for label in labels"

      



Second, ng-repeat doesn't work because you are using $index

on ng-value

, but the value in ng-model

has no index associated with it.

To make your code work with ng-repeat

, you can simply use ng-selected

in the <option>

following way:

  <option  ng-repeat="label in labels" ng-selected = "{{label == testVal}}"  ng-value="$index">
    {{label}}
  </option>

      

Here's an updated plunkr

0


source







All Articles