user3122203
user3122203

Reputation: 33

why this angularjs ng-model not update to the right value?

function buildControl($scope){
    $scope.test_obj = {
        used:3,
        data:[{id:1},{id:2},{id:3},{id:4}]
    };
}

<div ngApp>
    {{test_dict.used}}
    <select ng-model="test_obj.used">
        <option ng-repeat=" d in test_obj.data" value="{{d.id}}">{{d.id}}</option>
    </select>
</div>

why the selector always select the first option while I expect it will select the third one which's value equal 3?

Upvotes: 3

Views: 1333

Answers (2)

Banana-In-Black
Banana-In-Black

Reputation: 2557

Use ng-value instead.

http://jsfiddle.net/bateast/LsEL5/

HTML:

<option ng-repeat=" d in test_obj.data" ng-value="d.id">{{d.id}}</option>

JS:

function buildControl($scope){
    $scope.test_obj = {
        used:3,
        data:[{id:1},{id:2},{id:3},{id:4}]
    };
}

Upvotes: 6

dfsq
dfsq

Reputation: 193261

And you can also use ng-options directive to do that:

<div ng-app ng-controller="buildControl">
    {{test_obj.used}}
    <select ng-model="test_obj.used"
            ng-options="d.id as d.id for d in test_obj.data"></select>
</div>

Demo Plunker.

Upvotes: 7

Related Questions