AngularJS selecting multiple options

前端 未结 1 1279
说谎
说谎 2020-12-24 08:00

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 upda

相关标签:
1条回答
  • 2020-12-24 08:06

    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/

    0 讨论(0)
提交回复
热议问题