如何在 md-multiple-select 中限制 selection 选项?

How to restrict selection of options in md-multiple-select?

我需要将用户限制为 select 多 select 选项中只有 2 个选项.....我检查了 multiple-limit="value here" 这样的多限制... 这里是Codepen.....

正如我在问题评论中所读到的那样,限制选择(目前)还不受指令开箱即用的支持。但是,我们可以通过以下解决方法来实现类似的目标:

我们将添加一个 ng-change 来侦听指令的 ng-model 并为我们提供最新值。然后我们判断最新的值是否超过了选择的限制,如果是,我们为模型分配一个先前保存的具有最大选择的副本。

假设下例中的限制为 2:

$scope.changed = function(val) {
  if(val && val.length > 2) {
    $scope.myModel = $scope.prevModel;
  } else {
    $scope.prevModel = val;
  }
}

Working codepen

抱歉回答晚了,这是我的自定义指令:

https://codepen.io/anon/pen/bRoNWx

link: function(scope, element, attrs, ngModel) {
      scope.$watch(function () {
              return ngModel.$modelValue;
           }, function(newValue, oldValue) {
               if (newValue && newValue.length > attrs.mdSelectMaxSelection) {
                 ngModel.$setViewValue(oldValue);
                 ngModel.$render();
               }
           });
    }

您还可以为模型使用验证器,并通知用户为什么不能 select 更多元素。此外,您可以直接在模板中使用验证器名称。

更多信息:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController