javascript Angularjs:表单验证和输入指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21460923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs: form validation and input directive
提问by Adrian Wajs
I created a directive in an AngularJS app which produces styled input in my application. It looks like this:
我在 AngularJS 应用程序中创建了一个指令,它在我的应用程序中生成样式输入。它看起来像这样:
AC.directive('formInput',function ($compile) {
return {
transclude: true,
replace: true,
scope:{},
templateUrl: '/views/partials/form/input.html',
restrict: 'E',
link: function(scope, element, attrs){
scope.opts = attrs;
if(attrs.ngModel){
element.find('input').attr('ng-model', attrs.ngModel);
$compile(element.contents())(scope.$parent);
}
if(!attrs.type){
scope.opts.type = 'text';
}
}
};
}
)
And the template for it is:
它的模板是:
<label class="acxm-textfield {{opts.cssclass}}">
<span ng-bind="opts.labeltext"></span>
<input type="{{opts.type}}" name="{{opts.inputname}}" value="{{opts.inputvalue}}" placeholder="{{opts.placeholder}}" ng-maxlength="{{opts.maxLength}}"/>
</label>
The call is simple:
调用很简单:
<form-input ng-model="UserProfile.FirstName" max-length="50" labeltext="{{'GENERAL.name' | translate}}" cssclass="acxm-p-horizontal" inputname="name" inputvalue="{{UserProfile.FirstName}}"></form-input>
I wanted to create validation for this field and I added an error information:
我想为此字段创建验证并添加了错误信息:
<span ng-show="showError(userInfoForm.name,'email')">
You must enter a valid email
</span>
And showError is:
而 showError 是:
$scope.showError = function(ngModelController, error) {
return ngModelController.$error[error];
};
Basically, it is copied from the book "Mastering Web Application Development with AngularJS". I have a problem because when I log my form, which name is userInfoForm
, in console I got {{opts.inputname}}
instead of name property which value here should be "name". What am I doing wrong?
基本上,它是从“Mastering Web Application Development with AngularJS”一书中复制而来的。我有一个问题,因为当我登录我的表单时,哪个 name 是userInfoForm
,在控制台中,我得到的{{opts.inputname}}
不是 name 属性,这里的值应该是“name”。我究竟做错了什么?
回答by Khanh TO
Try my dynamic-name
directive here: AngularJS dynamic form field validation
dynamic-name
在这里尝试我的指令:AngularJS dynamic form field validation
Replace name="{{opts.inputname}}"
with dynamic-name="opts.inputname"
替换name="{{opts.inputname}}"
为dynamic-name="opts.inputname"
I also simplified your code for demonstration:
我还简化了您的演示代码:
app.directive("dynamicName", function($compile) {
return {
restrict: "A",
terminal: true,
priority: 1000,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.dynamicName);
if (name) {
element.attr('name', name);
element.removeAttr("dynamic-name");
$compile(element)(scope);
}
}
};
});
app.directive('formInput', function($compile) {
return {
replace: true,
scope: {},
templateUrl: 'formInput.html',
restrict: 'E',
link: function(scope, element, attrs) {
scope.opts = attrs;
$compile(element.contents())(scope);
}
}
});
Form Input template:
表单输入模板:
<label class="acxm-textfield {{opts.cssclass}}">
<span ng-bind="opts.labeltext"></span>
<input type="{{opts.type}}" dynamic-name="opts.inputname" ng-model="opts.inputvalue"
placeholder="{{opts.placeholder}}"
ng-maxlength="{{opts.maxLength}}" required/> //use dynamic-name directive to bind dynamic names.
</label>
DEMO(try clearing the text to see the validation, I used required validation for quick demonstration, you could change the code to email validation). The key is using the dynamic-name
directive.
DEMO(尝试清除文本以查看验证,我使用必需验证进行快速演示,您可以将代码更改为电子邮件验证)。关键是使用dynamic-name
指令。
回答by SoEzPz
Here is another take on form / name validation directives stacklink
这是另一种形式/名称验证指令 堆栈链接
<form name="myFormName">
<nested directives of many levels>
ex: <input ng-repeat=(index, variable) in variables" type="text"
my-name="{{ variable.name + '/' + 'myFormName' }}"
ng-model="variable.name" required />
ex: <select ng-model="variable.name" ng-options="label in label in {{ variable.options }}"
my-name="{{ variable.name + '/' + 'myFormName' }}"
</select>
</form
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^
app.directive('rsName', function(){
var rsNameError = "rsName directive error: "
return {
restrict:'A', // Declares an Attributes Directive.
require: 'ngModel', // ngModelController.
link: function( scope, elem, attrs, ngModel ){
if( !ngModel ){ return } // no ngModel exists for this element
// check rsName input for proper formatting ex. something/something
checkInputFormat(attrs);
var inputName = attrs.rsName.match('^\w+').pop(); // match upto '/'
assignInputNameToInputModel(inputName, ngModel);
var formName = attrs.rsName.match('\w+$').pop(); // match after '/'
findForm(formName, ngModel, scope);
} // end link
} // end return
function checkInputFormat(attrs){
if( !/\w\/\w/.test(attrs.rsName )){
throw rsNameError + "Formatting should be \"inputName/formName\" but is " + attrs.rsName
}
}
function assignInputNameToInputModel(inputName, ngModel){
ngModel.$name = inputName
}
function addInputNameToForm(formName, ngModel, scope){
scope[formName][ngModel.$name] = ngModel; return
}
function findForm(formName, ngModel, scope){
if( !scope ){ // ran out of scope before finding scope[formName]
throw rsNameError + "<Form> element named " + formName + " could not be found."
}
if( formName in scope){ // found scope[formName]
addInputNameToForm(formName, ngModel, scope)
return
}
findForm(formName, ngModel, scope.$parent) // recursively search through $parent scopes
}
});