1

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);
            }
        },
    }
}]);
Nicklas Kevin Frank
  • 6,079
  • 4
  • 38
  • 63

3 Answers3

4

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

karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • You have no idea how much time you just saved me - would have been nice finding out why the other method did not work though! – Nicklas Kevin Frank Jul 07 '14 at 12:50
  • It will not help, for example, if you intent to add 'checked' attribute to radio-button (because even checked="false" will check it). In cases like that check for a dedicated angular directive (ng-checked in this case). – Alexander Jan 01 '15 at 17:44
3

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);
                        }
                    },
                }
            }]);
Alexandre Nucera
  • 2,183
  • 2
  • 21
  • 34
  • I use this i my form input directice. when using $compile(element)(scope); It works but i get undefined – Abel D Jul 22 '15 at 19:26
1

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;
})
vipulsodha
  • 624
  • 1
  • 9
  • 27