在如下的指令中,我们如何在指令中通过属性传递的其他元素上手动设置验证。下面的代码给出了错误otherField不存在,而它应该取这个变量的值而不是范围字符串中该字段的直接名称。
app.directive('higherThan', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var otherField = $attrs.otherField;
$scope.otherField.$setValidity('lowerThan', true);
//Other details of directive not kept for simplicity
}
return {
require: 'ngModel',
link: link
};
}
]);
HTML
<form name="main_form">
<label>From</label>
<input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close" />
<label>To</label>
<input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="from_date"/>
<span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span>
</form>
答案 0 :(得分:1)
var otherField = $attrs.otherField;
$scope.otherField.$setValidity('lowerThan', true);
这里有一些问题:
1)var otherField
是一个字符串,而不是实际的输入。
2)一旦你设置var otherField
,你实际上并没有使用它。
3)没有属性$scope.otherField
,这就是你收到错误的原因。
即使您执行$scope[otherField]
,这也会出错,因为from_date
的ngModelController不属于$scope
,它属于main_form
。
您应该尝试使用console.log($scope)
进行调查。
应该是:
app.directive('higherThan', [
function($parse) {
var link = function($scope, $element, $attrs, ctrl) {
var otherField = $parse($attrs.otherField)($scope);
otherField.$setValidity('lowerThan', true);
//Other details of directive not kept for simplicity
}
return {
require: 'ngModel',
link: link
};
}
]);
<form name="main_form">
<label>From</label>
<input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close" />
<label>To</label>
<input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="main_form.from_date" />
<span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span>
</form>
答案 1 :(得分:0)
$setValidity
对象上调用 NgModelController
:
var link = function($scope, $element, $attrs, ctrl) {
var otherField = $attrs.otherField;
ctrl.$setValidity('lowerThan', true);
//Other details of directive not kept for simplicity
}