required or ng-required not working with ui-select 'multiple' option
required or ng-required=true is working fine with ui-select when the control is expected to select single value. However, with 'multiple' option, it is not working. The model presumes the value as array [], and marks it as valid=true.
Am I the only one facing this issue? Is this issue already addressed in the next version?
I found this solution here
angular.module('common').directive('uiSelectRequired', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$validators.uiSelectRequired = function (modelValue, viewValue) {
var determineVal;
if (angular.isArray(modelValue)) {
determineVal = modelValue;
} else if (angular.isArray(viewValue)) {
determineVal = viewValue;
} else {
return false;
}
return determineVal.length > 0;
};
}
};
});
add ui-select-required
Thanks imaa! It is working well. The error msg also started showing up when I change the condition from: ng-show="abcForm.tasks.$error.required" to ng-show="abcForm.tasks.$invalid"
Wondering, can this be merged with the main repository or with ng-required itself with more sophistication to handle $error.required as well?
ng-required or only required not work with "<ui-select multiple tagging" for me too. Component in form validation not detect state $scope.myform.$valid or $scope.myform.$invalid.
I confirm the behaviour - when multiple is set required is not working.
I just submitted a PR to fix this issue. It will allow you to just put required directly on the multiple tag and receive the expected functionality.
PR Link: https://github.com/angular-ui/ui-select/pull/1025
That's great Cole. Thank you.
The solution above works for me as well. Thanks!
@improvisio how did you get the solution above working? I added the module then added ui-select-required in the ui-select tag but its not working.
@GilbertChan I first added the directive as shown above: https://github.com/angular-ui/ui-select/issues/914#issuecomment-100962567 Then it worked. ui-select-required is not part of the ui-select package.
Thanks, @imaa it works!
@jcolemorrison
Check only required param doesn't work for me if i set ng-required="true", but code below works fine
if (angular.isDefined(attrs.multiple) && (angular.isDefined(attrs.required) || angular.isDefined(attrs.ngRequired)) ) {
My solution
angular.module('angularApp')
.directive('uiRequired', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.required = function(modelValue, viewValue) {
return !((viewValue && viewValue.length === 0 || false) && attrs.uiRequired === 'true');
};
attrs.$observe('uiRequired', function() {
ctrl.$setValidity('required', !(attrs.uiRequired === 'true' && ctrl.$viewValue && ctrl.$viewValue.length === 0));
});
}
};
});
@macem Thanks alot that helped
@macem Thanks as well, I've just used it and it works perfectly!
Resolved by #1492