问题
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