简体   繁体   中英

Angular JS: “Select All” options of “multi-select select box”

I have created a multiselect select box using Angular JS: below is the code for the same:

JS:

$scope.foobars = [{
    'foobar_id': 'foobar01',
    'name': 'foobar01',
}, {
    'foobar_id': 'foobar02',
    'name': 'foobar02',
}, {
    'foobar_id': 'foobar03',
    'name': 'foobar03',
}, {
    'foobar_id': 'foobar04',
    'name': 'foobar04',
}, {
    'foobar_id': 'foobar05',
    'name': 'foobar05',
}];

HTML:

<select multiple="multiple" size="5" id="selFooBar" ng-model="foobarName" ng-options="medcenter as medcenter.name for medcenter in medcenters track by medcenter.medcenter_id">
    <option selected="selected">Select All</option>
</select>

And the output is :

在此处输入图片说明

Question 1: Why am I not getting the default option "Select All" in the list? And How do I get that?

Question 2: How can I Select All optiions on click of "First Option : Select All"??

Please suggest!

If you want to keep the <option> in the <select> element before you add the ng-options you'll have to use transclusion. the ng-options directive doesn't use transclusion, but you can create a custom directive that does. You can do that by utilizing transcludeFn in the directive post compile function:

compile: function(element,attrs) {
  return {
    post: function(scope, element, attributes, controller, transcludeFn){
      transcludeFn(function(clone, scope) {
        // prepend the transcluded content to the select
        element.prepend(clone);
        // set the onclick of the clone to call the selectAll function
        clone.bind('click', function(){
          clone.scope().$parent.selectAll();
          scope.$apply();
        })
      });
    }
  }
},
controller: function($scope) {
  $scope.selectAll = function() {
    $scope.selectedValues = $scope.values;
  }
}

Then you can set the selectedValues to all possible values on the scope, whether that's isolate or inherited. In the following plnkr example it's isolated. On click the Select All option will select the other elements. Plunker Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM