【发布时间】:2013-07-02 16:18:20
【问题描述】:
我想制作自己的 Angular 指令并在其上使用表单验证。这将允许我在其他地方重用这部分表单。实际的代码是不同的,但我觉得我在这里想错了。首先我做了一个表格:
<form name="check1">
<input name="first" ng-model="first" type="text" required>
<input name="second" ng-model="second" type="text" required>
<input name="third" ng-model="third" type="text" required>
</form>
<span ng-show="check1.$invalid">Form is invalid</span>
验证工作正常。然后我希望我的表单类似于:
<form name="check2">
<input name="first" ng-model="first" type="text" required>
<mydirective second="second" third="third" required></mydirective>
</form>
<span ng-show="check2.$invalid">Form is invalid</span>
和JS:
app.directive('mydirective', function() {
return {
restrict: 'E',
transclude: true,
template:
'<span>'+
'<input name="second" ng-model="second" type="text" >'+
'<input name="third" ng-model="third" type="text" >'+
'</span>'
,
replace: true,
scope: {
second: '=',
third: '='
}
}
});
如何使验证工作?现在填写“first”将使check2表单有效。
我已经尝试将链接功能添加到控制器:
link: function(scope, element, attrs, controller) {
controller.$parsers.unshift(function(viewValue)
console.log(viewValue);
return viewValue;
});
}
但我得到了:
TypeError: Cannot call method 'unshift' of undefined
任何想法我做错了什么?
编辑
看来我的问题写得不太好。我正在寻找在 Angular 指令中有条件地“必需”字段的可能性。所以制作:
<mydirective second="second" third="third" required></mydirective>
将使指令字段成为必需,而这不会:
<mydirective second="second" third="third"></mydirective>
解决方案是在链接功能和ng-required中使用attrs。所以:
app.directive('mydirective', function() {
return {
template:
'<span>'+
'<input name="second" ng-model="second" type="text" ng-required="is_required">'+
'<input name="third" ng-model="third" type="text" ng-required="is_required">'+
'</span>'
,
link: function(scope, iElement, iAttrs) {
scope.is_required = angular.isDefined(iAttrs.required)
}
}
});
【问题讨论】:
-
为什么要设置双向绑定?
-
@Ajaybeniwal:我想在“check2”的范围内初始化“second”和“third”。用户将在指令范围内更改其值,并再次在“check2”范围内使用它们(保存到服务器 - 此 sn-p 中未显示)。
标签: validation angularjs directive