AngularJS ui-select 如果超过限制,多个应显示警报

AngularJS ui-select multiple should show alert if limit is crossed

在AngularJSui-select多个中,我可以给它添加一个限制,或者创建一个警报。但我无法做到这两点。如果我显示警报,则不会从 UI 中清除之前的 selected 选项。代码笔:https://codepen.io/pragatij55/pen/mdpzmqp

我知道我可以使用 limit="2",但我还想要一个警报。

<div ng-app="demo" class="ng-cloak" ng-controller="DemoCtrl">
  
  <ui-select multiple ng-model="myModel" theme="bootstrap" ng-disabled="disabled" close-on-select="false" style="width: 800px;" on-select="changed(myModel)" title="Choose a person">
    <ui-select-match placeholder="Select person...">{{$item.name}}</ui-select-match>
    <ui-select-choices repeat="person.name as person in people | propsFilter: {name: $select.search, type: $select.search}">
      <div ng-bind-html="person.name | highlight: $select.search"></div>
      <small>
       
        type: <span ng-bind-html="''+person.type | highlight: $select.search"></span>
      </small>
    </ui-select-choices>
  </ui-select>
  
</div>

JS:

app.controller('DemoCtrl', function ($scope, $http, $timeout, $interval) {
  $scope.people = [
    { name: 'var1',      type: 'header' },
    { name: 'var2',  type: 'site' },
    { name: 'var3',  type:'header' },
    { name: 'var4',  type:'header' }
  ];
  $scope.changed = function(val) {
      if(val && val.length > 2) {
       $scope.myModel = $scope.prevModel;
       alert("Upto 2 variables can be selected")
     } else {
       $scope.prevModel = val;
       
     }
  }
  
});

不确定这是否是您想要的,但您可以在此处使用 Array.pop() 删除警报之前的第 3 项:

$scope.changed = function(val) {
      if(val && val.length > 2) {
       val.pop();

在上下文中:

app.controller('DemoCtrl', function ($scope, $http, $timeout, $interval) {
  $scope.people = [
    { name: 'var1',      type: 'header' },
    { name: 'var2',  type: 'site' },
    { name: 'var3',  type:'header' },
    { name: 'var4',  type:'header' }
  ];
  $scope.changed = function(val) {
      if(val && val.length > 2) {
       val.pop(); // <- add this line
       $scope.myModel = $scope.prevModel;
       alert("Upto 2 variables can be selected")
     } else {
       $scope.prevModel = val;
       
     }
  }
  
});