简体   繁体   中英

Creating a custom angular directive for tag and attribute combination?

Ok, here's the deal.

I created a custom directive for the input tag with custom validation for input[type=ip] :

.directive('input', function($q, $timeout) {
    return {
        restrict: "E",
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            if (attrs.type !== 'ip') return;
            var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
            ctrl.$asyncValidators.ip = function(modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    return $q.when();
                }

                var def = $q.defer();
                if(reg.exec(modelValue)) {
                    def.resolve();
                } else {
                    def.reject();
                }

                return def.promise;
            };
        }
    };
});

This works fantasticaly and I plan on using it to create custom validations in the future.

The issue I'm having is with input[type=file] . In the view, it has no ngModel attribute. Angular does not like this. It's technically an input tag so it interprets the input directive... but that requires the ngModel attribute.

How can I fix this? How can I create custom input directives based upon the type attribute that don't break each other?

Can I make the require: 'ngModel' somehow options or something?

Phil's comment of using ?ngModel fixed it. Everything working fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM