AngularJS selecting multiple options

2019-01-31 23:52发布

So, What I'm trying to do is fairly simple with vanilla JS, but I'm using AngularJS and I would like to know how to do it the best way within the framework. I want to update the selected options in a multiple select box. I do not want to add or remove any of the options. Here is what my HTML looks like:

<select multiple>
    <option value="1">Blue</option>
    <option value="2">Green</option>
    <option value="3">Yellow</option>
    <option value="4">Red</option>
</select>

Using the following array, I'd like to programmatically select/deselect options from this list:

[{id:1, name:"Blue"},{id:4, name:"Red"}]

When I set this array in the scope, I want the select box to deselect anything that is not Blue or Red and select Blue and Red. The standard response that I've seen on the Google Groups is to use ng-repeat. However, I can't recreate the list every time because the list of selected values is incomplete. As far as I can tell, AngularJS has no mechanism for this, and I'm at a loss as to how I would do this without resorting to using jQuery.

1条回答
乱世女痞
2楼-- · 2019-02-01 00:09

ngModel is pretty awesome! If you specify the indexes as a model selectedValues

<select multiple ng-model="selectedValues">

built from your list (selected) in a $watch

$scope.$watch('selected', function(nowSelected){
    // reset to nothing, could use `splice` to preserve non-angular references
    $scope.selectedValues = [];

    if( ! nowSelected ){
        // sometimes selected is null or undefined
        return;
    }

    // here's the magic
    angular.forEach(nowSelected, function(val){
        $scope.selectedValues.push( val.id.toString() );
    });
});

ngModel will automatically select them for you.

Note that this data binding is one-way (selected to UI). If you're wanting to use the <select> UI to build your list, I'd suggest refactoring the data (or using another $watch but those can be expensive).

Yes, selectedValues needs to contain strings, not numbers. (At least it did for me :)

Full example at http://jsfiddle.net/JB3Un/

查看更多
登录 后发表回答