Vlado Pandžić
Vlado Pandžić

Reputation: 5048

angular select inside ng-repeat

I have situation like this:

<span ng-repeat="personNum  in unit.PricePerson">
      {{personNum}}
      <select ng-model="personNum" 
              ng-options="o as o for o in unit.PricePerson track by $index"></select>
</span>

unit.Price are numbers array,something like [5,6,7,8,9] but each select has value of nine. I want that first select selected option 5,other one 6, etc. Also, i noticed I can not change options using mouse.

There are 5 select boxes generated which is fine, there are also number from 5 to 9 generated as options inside each select. Those things are ok.

Upvotes: 1

Views: 1759

Answers (3)

brae
brae

Reputation: 1122

Your question a little unclear, but it looks like you are having issues with your ng-options configuration.

It's generally not recommended to use select as with track by, as they are not designed to work together and can have unexpected results. Also, you are using the unit.PricePerson reference inside your ng-options instead of the individual iteration object personNum.

You should have something like:

<span ng-repeat="personNum in unit.PricePerson">
      {{personNum}}
      <select ng-model="personNum.selectedOption" 
              ng-options="o as o for o in unit.PricePerson">
      </select>
</span>

However, without seeing your javascript object PricePerson, I can't be certain what your ng-options configuration should be. Have a look at the AngularJS API for ngOptions. In the Arguments section, there are suggested templates for your ng-options expression.

Upvotes: 0

changtung
changtung

Reputation: 1624

Try to use different ng-model inside select, than in ng-repeat and initiate it to have desired value:

<span ng-repeat="personNum  in unit.PricePerson">
      {{personNum}}
      <select ng-init="personNum1 = personNum" ng-model="personNum1" 
              ng-options="o as o for o in unit.PricePerson track by $index"></select>
</span>

etc.


So, to complete this. Look that you use same ng-model, that is why you cannot change options with a mouse. In your controller, create an array of options:

    $scope.selectedOptions = ['5','6','7','8','9'];

Then use it in your view:

          <select ng-model="selectedOptions[$index]" 
              ng-options="o as o for o in unit.PricePerson track by $index">

Upvotes: -1

DWDuck
DWDuck

Reputation: 239

Part of your problem might be the track by $index in your select... Have a look at the plunker below. Also, use ng-init to set a default value.

http://plnkr.co/edit/2ZN1J61PD1Ev2OK1tezg

The code:

<span ng-repeat="personNum  in unit.PricePerson">
  <select ng-init="select[$index]=personNum" ng-model="select[$index]" ng-options="o as o for o in unit.PricePerson">

  </select>
</span>

As @cyan suggested, I think you also need the ng-model to be something other than the variable in your outer ng-repeat.

Hope this helps.

Upvotes: 3

Related Questions