更新选项时,使用ng-repeat的角度选择会丢失所选选项

时间:2015-10-19 22:25:51

标签: javascript angularjs

我正在尝试使用AngularJS为动态列表创建编辑器。对于每个项目,我想添加一个包含列表中所有元素选项的选择列表。当项目添加到列表(JSFiddle中的“添加”按钮)时,其他选项将丢失其值。该模型不受此影响,仅受视图影响。我错过了什么?

这是我的JSFiddle

查看:

<div ng-controller="selectDemoCtrl">{{msg}}
    <table>
        <tr>
            <td>id</td>
            <td>references</td>
        </tr>
        <tr ng-repeat="item in items">
            <td>
                <input ng-model="item.id" type="number">
            </td>
            <td>
                <select ng-model="item.ref">
                    <option ng-repeat="i in items" value="i.id" ng-selected="item.ref==i.id">{{i.id}}</option>
                </select>
                </td>
        </tr>
    </table>
    <button ng-click="addItem()">Add</button>
    <div>{{items | json}}</div>
</div> 

控制器:

selectDemo.controller('selectDemoCtrl', function ($scope) {
    $scope.items = [{
        id: 1,
        ref: 2
    }, {
        id: 2,
        ref: 1
    }];

    $scope.addItem = function(){
        var newitem = {id: 1, ref:1};
        for (var i = 0; i < $scope.items.length; i++){
            if ($scope.items[i].id >= newitem.id) { newitem.id = $scope.items[i].id + 1; }
        }
        if ($scope.items.length > 0){newitem.ref = $scope.items[0].id;}
        $scope.items.push(newitem);
    };
});

1 个答案:

答案 0 :(得分:3)

不要使用ngRepeat,它对于绑定模型不可靠。请改用ngOptions,它应该按预期工作:

<select ng-options="i.id as i.id for i in items" ng-model="item.ref"></select>

演示: https://jsfiddle.net/4bemy5wj/1/