简体   繁体   中英

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

In AngularJS ui-select multiple, I can add a limit to it, or create an alert. But I'm not able to do both. If I show the alert, the previous selected options are not cleared from the UI. Codepen: https://codepen.io/pragatij55/pen/mdpzmqp

I know I can use limit="2", but I also want an alert.

<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;
       
     }
  }
  
});

Not sure if this is what you want, but you can remove that 3rd item right before the alert with Array.pop() right here:

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

In context:

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;
       
     }
  }
  
});

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