Aditya Sethi
Aditya Sethi

Reputation: 10586

select in ng-option does not update

I have the list of data that is coming from backend and I want to update the select value in the view which is not happening for some reason.

I tried ng-selected that does not works efficiently, sometime the model is update spmetimes not.

here is my code, can someone help?

    <div class="listitem" ng-repeat="d in data">
        {{d.name}}: 
        <select 
            ng-model="d.option"                 
            ng-options="d.name for d in options"></select>
    </div>

Controller

var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
    $scope.options = [{
        "id": "id1",
        "name": "p1"
    }, {
        "id": "id2",
        "name": "p2"
    }];
    $scope.data = [{
        "name": "data1",
        "option": {
            "id": "id1",
            "name": "p1"
        }
    }];
});

http://jsfiddle.net/gFCzV/58/

Upvotes: 4

Views: 10258

Answers (2)

csharpfolk
csharpfolk

Reputation: 4290

You have in your code:

 $scope.options = [{
     "id": "id1",
     "name": "p1"
 }, {
     "id": "id2",
     "name": "p2"
 }];

 $scope.data = [{
     "name": "data1",
     "option": {
         "id": "id1",
         "name": "p1"
     }
 }];

but Angular doesn't know that first option object used in $scope.options collection is same as option used in $scope.data.

I can suggest two solutions:

  1. In $scope.data keep only option identifier "option": "id1" and in ng-options use d.id as d.name for d in options

  2. In ng-options use "ng-options="d as d.name for d in options" and initialize $scope.data options like "option": $scope.options[0], but since it is coming from backend you may need to fix references manually.

Options 1 is better IMHO.

EDIT: Example JSFIDDLE was created in Angular 1.1, if you use Angular 1.2 or later @Satpal track by answer is also good option (no pun).

Upvotes: 0

Satpal
Satpal

Reputation: 133453

You need to use select as label group by group for value in array track by trackexpr, Read DOCs

ng-options="option.name for option in options track by option.id"

DEMO, However note this will not work in Angualrjs 1.1

Upvotes: 3

Related Questions