在多项选择

时间:2018-03-26 13:32:30

标签: javascript angularjs select multiple-select

我在.html页面中有一个下拉列表作为多重选择:

 <select class="form-control"
         multiple
         ng-model="filter.types"
         ng-change="onChange()"
         ng-options="option for option in filterOptions.types">
    {{option}}
 </select>

在我的控制器中,我有onChange功能:

$scope.onChange= function(newOptionSelected){
    console.log(newOptionSelected);
}

这里我想将当前项添加到选定的filter.types中。 我怎么能实现这个目标?

如果是单个选择,我可以简单地将ng-model传递给onChange函数。

<select class="form-control"
     ng-model="filter.type"
     ng-change="onChange(filter.type)"
     ng-options="option for option in filterOptions.types">
{{option}}

但如何通过多重选择来实现这一目标?

有什么想法吗? :)

如果添加的选项是“全部”,我想删除所有选中的元素。如果选择“全部”选项,那么当我选择下一个项目时,我只需要删除“全部”选项。

enter image description here

2 个答案:

答案 0 :(得分:0)

使用ng-change无法实现此目的,因为您需要跟踪上次选择的选项。您必须$watch filter.types这是一个数组,然后根据新值和旧值,您可以决定要做什么。

$scope.$watch('filter.types', function(newVal, oldVal) {
      if (newVal.length > oldVal.length) { //Updating only on selecting 
        var lastSelectedOption = [];
        lastSelectedOption = $scope.diff(newVal, oldVal);
        if (lastSelectedOption[0] == 'All') { 

          var i = newVal.length;
          while (i--) {
            if (newVal[i] != 'All') {
              newVal.splice(i, 1); //Deleting other options
            }
          }
        } else if (newVal.indexOf('All') > -1) { 
          newVal.splice(newVal.indexOf('All'), 1); //Deleting 'All' option
        }
      }

    });

工作JSFiddle link供您参考。祝你好运!

答案 1 :(得分:-1)

您可以查看角度的文档以获得此问题的答案。 https://docs.angularjs.org/api/ng/directive/select

Plunker:- https://plnkr.co/edit/rhX9AiAhPfHXB2c2BUZF?p=preview