Simple custom directive add ng-attribute to input element

半腔热情 提交于 2019-12-11 18:49:55

问题


I have been trying to create a very simple directive that checks if the attribute my-minlength is a string (not null) and if it is; add the attribute ng-minlength to the input element. I feel like this should work, but it is simply not working.

My Directive

var app = angular.module("fooApplication", [])

app.directive('myMinlength', function() {
    return {
        link: function(scope, element, attrs) {
            if(element == "") {
                attrs.$set('ng-minlength', attrs.myMinlength);
            }
        },
    }
});

My HTML

<input type="text" name="foo" my-minlength="5" required/>

Edit the suggestion completely stripped from possible errors - still does not work.

.directive('myMinlength', ['$compile', function($compile) {
    return {
        link: function(scope, element, attrs) {
           if(true) {
                attrs.$set('ng-minlength', "5");
                $compile(element)(scope);
            }
        },
    }
}]);

回答1:


You can use simpler approach:

<input type="text" name="foo" ng-minlength="myvar || 0" required/>

if scope.myvar is undefined then minlength will be 0




回答2:


You need to recompile your directive in order to add the ng-minlength attribute to your directive. Try this :

.directive('myMinlength', ['$compile', function($compile) {
                return {
                    link: function(scope, element, attrs) {
                       if(element == "") {
                            attrs.$set('ng-minlength', attrs.myMinlength);
                            $compile(element)(scope);
                        }
                    },
                }
            }]);



回答3:


you should use compile

 .directive('myMinlength', function() {
    var directive = {};

    directive.restrict = 'A'; /* restrict this directive to attributess */

    directive.compile = function(element, attributes) {


        var linkFunction = function($scope, element, attributes) {
           attributes.$set('ng-minlength', attrs.myMinlength);
        }

        return linkFunction;
    }

    return directive;
})


来源:https://stackoverflow.com/questions/24610590/simple-custom-directive-add-ng-attribute-to-input-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!