简单的自定义指令将 ng-attribute 添加到输入元素 [英] Simple custom directive add ng-attribute to input element
本文介绍了简单的自定义指令将 ng-attribute 添加到输入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试创建一个非常简单的指令,用于检查属性 my-minlength
是否为字符串(非空)以及是否为;将属性 ng-minlength
添加到输入元素.我觉得这应该可行,但根本行不通.
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.
我的指令
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/>
编辑建议完全排除可能的错误 - 仍然不起作用.
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);
}
},
}
}]);
推荐答案
您可以使用更简单的方法:
You can use simpler approach:
<input type="text" name="foo" ng-minlength="myvar || 0" required/>
如果 scope.myvar 未定义,则 minlength 将为 0
if scope.myvar is undefined then minlength will be 0
这篇关于简单的自定义指令将 ng-attribute 添加到输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文