item selected and selectable in ui-select2

613 Views Asked by At

Usually, an item is removed from the list of selectable items, after being selected.
But, when I refresh the underlying list of items, the (already) selected items, are selectable too!
How can i avoid this?

My view looks like this:

<div ng-controller="MyCtrl" ng-init=buildList()>
    <button ng-click="buildList()">Refresh list</button>

    <select multiple ui-select2 data-ng-model="selectedDaltons">
        <option data-ng-repeat="dalton in daltons" value="{{dalton.id}}">
            {{dalton.name}}
        </option>
    </select>
</div>

My controller:

function MyCtrl($scope) {
    // Averell is preselected (id:4)
    $scope.selectedDaltons = [4]; 

    // $scope.daltons is iterated in ng-repeat
    // its initially called in ng-init
    $scope.buildList = function() {
        $scope.daltons = [
            { id: 1, name: 'Joe' },
            { id: 2, name: 'William' },
            { id: 3, name: 'Jack' },
            { id: 4, name: 'Averell' },
            { id: 5, name: 'Ma' }
        ];
    };
};

Here it is as a jsfiddle.

1

There are 1 best solutions below

0
On BEST ANSWER

Actually I think I found an solution (to my own question):

Based on the controller of the original question, change the array, before replacing it:

function MyCtrl($scope) {
    // Averell is preselected (id:4)
    $scope.selectedDaltons = [4]; 

    // $scope.daltons is iterated in ng-repeat
    // its initially called in ng-init
    $scope.buildList = function() {

        // touch array before renewal!! 
        if (angular.isArray($scope.daltons)) {
            $scope.daltons.pop();
        }

        $scope.daltons = [
            { id: 1, name: 'Joe' },
            { id: 2, name: 'William' },
            { id: 3, name: 'Jack' },
            { id: 4, name: 'Averell' },
            { id: 5, name: 'Ma' }
        ];
    };
};

Here the updated jsfiddle.