2

在角度上,如果需要,使用 Track by 按值而不是按引用来跟踪选择是一个不错的功能。但是假设我将数组切换到后面并且选定的对象 id 匹配一个新的 Id 我希望选择也改变

我如何强制它重新评估?

HTML:

    <select ng-options="option.id for option in collection track by option.id" ng-model="selectedObject"></select>
    <button ng-click="updateCollection()">Update</button>

JS:

    $scope.collection = [{
            id: 1,
            value: 0
        }, {
            id: 2,
            value: 0
        }, {
            id: 3,
            value: 0
        }];

    $scope.selectedObject = $scope.collection[0];

    $scope.updateCollection = function () {
        var newColl = [{
            id: 1,
            value: 100
        }, {
            id: 2,
            value: 200
        }, {
            id: 3,
            value: 300
        }];

        $scope.collection = newColl;

可以说我选择Id 2然后更新selectedObject仍然是旧的id:2 value:0,我希望它直接更改为id:2 value:200.

https://jsfiddle.net/IngoVals/p4ye3uaq/

PS为什么angular.copy小提琴中的工作不起作用?

4

1 回答 1

2

when you pick Id 2 then option model selectedObject is the second object of the collection which has Id of 2.

Then you press the update button and change $scope.collection at this point optoins will change in the select box, but the selected value is never changed, its still reference to the second object of the previous $scope.collection. so you need to update the selected value as well to do that,

get the selected object's index as,

 var selectedIndex = $scope.collection.indexOf($scope.selectedObject);

assign the new collection as you did,

$scope.collection = newColl;

finally update the selectedObject based on that previously selected object's index.

$scope.selectedObject = $scope.collection[selectedIndex];

here is the DEMO

于 2015-05-01T16:03:41.397 回答