Home > front end >  AngularJS ui-select multiple should show alert if limit is crossed
AngularJS ui-select multiple should show alert if limit is crossed

Time:04-15

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

CodePudding user response:

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