14

I'm using typeahead's UI Bootstrap component and I want to force the selection to validate my form.

Is it possible to configure it to set the input invalid when typeahead-editable is set to false and the user enters a "bad" value or I should write a directive for this (but how)?

Julien Meyer
  • 275
  • 1
  • 4
  • 12

2 Answers2

19

The typeahead directive from http://angular-ui.github.io/bootstrap/ has already support for limiting inputs to matches (in other words, people can bind to model only values available as matches in the typeahead popup). You can do this by simply setting typeahead-editable='false' attribute.

Please note that setting this attribute to false will not prevent people from typing-in invalid values. It will just make sure that a corresponding input is marked as invalid and a provided value is not bound to the model.

pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • I know that editable set to false allow the user to enter any value. It just not set the model. What I found strange is that the input field is not "invalid" when the user enter a not selectable value. : [Example ](http://plnkr.co/edit/KbLOIRKHK5PdEIPvBCFV?p=preview). Or I don't understand something... – Julien Meyer Aug 09 '13 at 07:35
  • @JulienMeyer I see - you would like also set validity flag accordingly, right? This sounds reasonable, feel free to open issue for this in https://github.com/angular-ui/bootstrap/issues?state=open – pkozlowski.opensource Aug 12 '13 at 12:15
  • Yes. I will create an issue. Thank you – Julien Meyer Aug 13 '13 at 07:26
  • I see that there is an issue created for this. https://github.com/angular-ui/bootstrap/issues/2308 I however do not see a fix... I suspect this is a $scoping issue. The model.$valid is set to false but I don't think it is in the same scope as the form when the user types... – chrislhardin Aug 03 '14 at 14:14
-1

Answer on the behalf of OP:

var formValidatorsModule = angular.module('app.validator.formValidator', []);

formValidatorsModule.directive('typeaheadForceSelection', function() {
    return {
        require : 'ngModel',
        link : function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                if (viewValue == undefined) {
                    ctrl.$setValidity('typeaheadForceSelection', false);
                } else {
                    ctrl.$setValidity('typeaheadForceSelection', true);
                }
                return viewValue;
            });
        }
    };
});