我一直在尝试创建一个非常简单的指令,检查属性my-minlength
是否为字符串(非空),如果是;将属性ng-minlength
添加到input元素。我觉得这应该有用,但它根本不起作用。
我的指示
var app = angular.module("fooApplication", [])
app.directive('myMinlength', function() {
return {
link: function(scope, element, attrs) {
if(element == "") {
attrs.$set('ng-minlength', attrs.myMinlength);
}
},
}
});
我的HTML
<input type="text" name="foo" my-minlength="5" required/>
编辑完全脱离可能的错误的建议 - 仍然无效。
.directive('myMinlength', ['$compile', function($compile) {
return {
link: function(scope, element, attrs) {
if(true) {
attrs.$set('ng-minlength', "5");
$compile(element)(scope);
}
},
}
}]);
答案 0 :(得分:4)
您可以使用更简单的方法:
<input type="text" name="foo" ng-minlength="myvar || 0" required/>
如果scope.myvar未定义,则minlength将为0
答案 1 :(得分:3)
您需要重新编译指令才能将ng-minlength属性添加到指令中。试试这个:
.directive('myMinlength', ['$compile', function($compile) {
return {
link: function(scope, element, attrs) {
if(element == "") {
attrs.$set('ng-minlength', attrs.myMinlength);
$compile(element)(scope);
}
},
}
}]);
答案 2 :(得分:1)
你应该使用编译
.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;
})