Reputation: 2075
I need to restrict the user to select only 2 options from the multi-select options.....i checked with multiple-limit like multiple-limit="value here"
...
Here is theCodepen....
Upvotes: 1
Views: 2504
Reputation: 306
Sorry for the late answer, here is my custom directive:
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();
}
});
}
Also you can use validators for the model, and notify the user why he cannot select more elements. Furthermore you can directly use the validator names in your template.
More info: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
Upvotes: 1
Reputation: 7911
As I read in the question comments, limiting selections is not (yet) supported out-of-the-box from the directive. But, we can have following workaround to get something like that achieved:
We would add a ng-change
which listens to the directive's ng-model
and gives us latest value. We then decide whether the latest value has exceeded the limit of selections, if so, we assign the model a previously saved copy with maximum selections.
Assuming the limit is 2 in the example below:
$scope.changed = function(val) {
if(val && val.length > 2) {
$scope.myModel = $scope.prevModel;
} else {
$scope.prevModel = val;
}
}
Upvotes: 2