Reputation: 10586
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"
}
}];
});
Upvotes: 4
Views: 10258
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:
In $scope.data
keep only option identifier "option": "id1"
and in ng-options
use d.id as d.name for d in options
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