Mik*_*son 7 javascript angularjs
我有一个自定义验证指令,我用它来确保两个日期在有效范围内.当用户更改值时,该指令工作正常,但是当我lineItem通过AJAX 加载新模型时它不会触发.
问题是用户可能在表单上输入无效日期并触发错误,然后加载另一个lineItem.此时,即使表单中的数据有效,表单上也会显示一条错误消息.
如果我使用Angular的内置验证(例如required)尝试相同的操作,则验证会触发并适当地消失.那么,我需要做什么才能使我的验证触发器与Angular相同?
(注意:我正在使用novalidate表单属性和Angular v1.1.5)
指示
ngApp.directive("validateBefore", function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function(value) {
var before = scope.$eval(attrs.validateBefore);
if(value <= before || !before) {
ctrl.$setValidity("validateBefore", true);
return value;
} else {
ctrl.$setValidity("validateBefore", false);
return undefined;
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
模板
<div class="date-group">
<span class="date">
<input type="text" class="input-medium" name="starts-at" ng-model="lineItem.startsAt" placeholder="From..." validate-before="lineItem.endsAt">
</span>
<span class="date">
<input type="text" class="input-medium" name="ends-at" ng-model="lineItem.endsAt" placeholder="To..." validate-after="lineItem.startsAt">
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
CONTROLLER
var lineItem = LineItem.get( { id: lineItemId }, function () {
$scope.lineItem = lineItem;
if($scope.lineItemForm) {
$scope.lineItemForm.$setPristine();
}
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*son 10
啊哈,我只占了等式的一半.在$parsers当输入与DOM的模型发送的火灾.我需要添加$formatters,它将数据从模型发送到DOM.
在$ parsers之后,我添加了以下内容:
ctrl.$formatters.unshift(function(value) {
var before = scope.$eval(attrs.validateBefore);
ctrl.$setValidity("validateBefore", before ? value <= before : true);
return value;
});
Run Code Online (Sandbox Code Playgroud)
这会导致验证在模型更改时触发.这里有更多讨论:http: //docs.angularjs.org/guide/forms,这里http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController#$formatters
| 归档时间: |
|
| 查看次数: |
8544 次 |
| 最近记录: |