【发布时间】:2014-02-23 00:25:15
【问题描述】:
我在 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';
}
}
};
}
)
它的模板是:
<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>
调用很简单:
<form-input ng-model="UserProfile.FirstName" max-length="50" labeltext="{{'GENERAL.name' | translate}}" cssclass="acxm-p-horizontal" inputname="name" inputvalue="{{UserProfile.FirstName}}"></form-input>
我想为此字段创建验证,并添加了错误信息:
<span ng-show="showError(userInfoForm.name,'email')">
You must enter a valid email
</span>
而 showError 是:
$scope.showError = function(ngModelController, error) {
return ngModelController.$error[error];
};
基本上,它是从《Mastering Web Application Development with AngularJS》一书中抄来的。我有一个问题,因为当我在控制台中记录名为userInfoForm 的表单时,我得到了{{opts.inputname}} 而不是名称属性,这里的值应该是“名称”。我做错了什么?
【问题讨论】:
-
看看我对类似问题的回答:stackoverflow.com/questions/21455695/…
-
在我发布的链接中声明指令并将
name="{{opts.inputname}}"替换为dynamic-name="opts.inputname" -
Khanh 是的,我可以创建一个指令,但由于我的输入已经是一个指令,我只添加了: element.find('input').attr('name', scope.opts.inputname);它添加了一个名称 attr 但我仍然无法进行验证:/ 在 showError 中,当我尝试访问我的字段时,ngModelController 仍然未定义...这是一个示例:plnkr.co/edit/xKktbdw1dP5elWKnmQMC?p=preview
-
是的,我认为你的言论很好......嗯,但如何让它发挥作用:)
-
我发现我的解决方案有效,只是忘记将
required放入我的输入字段。傻我。我张贴作为答案。请看一看。
标签: javascript html angularjs validation