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

僤鯓⒐⒋嵵緔 提交于 2019-12-12 03:26:16

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/28097484/angular-js-select-all-options-of-multi-select-select-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!