Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive to dynamically create an ng-pattern

I'm trying to create a directive for an input element that will dynamically create an ng-pattern to check for a valid IP address in the input field. All of my attempts to do so have been completely unsuccessful. While I can dynamically modify other attributes, I can't create an ng-pattern that will affect the $valid status.

Here's the code that I've been working on which seems like it should work, but it doesn't do anything to the ng-pattern.

app.directive('ipAddress', function($parse) {
    return {
        link: function(scope, element, attrs) {
            var model = $parse(attrs.ngPattern);
            model.assign(scope, "/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/");
            scope.$apply();
        };
});

Directive:

<input ng-model="ip" ip-address required type="text" id="inputIP" placeholder="xxx.xxx.xxx.xxx">

Yes, I know I can just specify the ng-pattern inline with the <input> tag but the point is that I want to be able to do this dynamically in the code, and I'd like to keep the <input> tag cleaner by not embedding a bunch of regex code there.

Can anyone please help me? Thanks!

like image 919
Dr. Cool Avatar asked Apr 16 '26 09:04

Dr. Cool


1 Answers

You can define pattern in controller and then use in html:

$scope.pat=/^.*$/

And then in html

<input ng-pattern="pat" ... >
like image 173
Piotr Winiarczyk Avatar answered Apr 17 '26 23:04

Piotr Winiarczyk