sailboatlie
sailboatlie

Reputation: 346

Angular Directive not working with Input type="number"

I have an input in a form that looks like this:

<input type="number" name="inputStageNumTeams" id="inputStageNumTeams"
 ng-model="s.numTeams" validate-greaterthan="2" required>

However, for some reason my custom directive validateGreaterthan isn't running correctly. If I change the input type to "text" it works like a charm! I'd like to keep the input type to number if possible.

Here is the directive in question:

app.directive('validateGreaterthan', function() {
return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
            var number = attrs.validateGreaterthan;
            if (parseInt(viewValue) !== NaN) {
                scope.numberValid = ((viewValue && (parseInt(viewValue) >= number)) ? 'valid' : undefined);
            }

            if(scope.numberValid) {
                ctrl.$setValidity('number', true);
                return viewValue;
            } else {
                ctrl.$setValidity('number', false);
                return undefined;
            }

        });
    }
};
});

Upvotes: 2

Views: 2209

Answers (2)

Laurent Zuijdwijk
Laurent Zuijdwijk

Reputation: 611

I am pretty sure that the attribute value (attrs.validateGreaterthan) is a string. Convert that string to an integer, to make sure you are comparing the same type.

Upvotes: 0

bbs
bbs

Reputation: 2022

Why do you not try to use the already existing [min="{string}"] directive?

http://docs.angularjs.org/api/ng.directive:input.number

Upvotes: 3

Related Questions