我创建了一个示例日期范围验证指令。
当开始日期大于结束日期时,我们必须抛出验证错误。如果我通过更新开始日期文本框中的值来更改开始日期的值,则验证工作正常。但是当我使用控制器事件更改开始日期的值时不会触发验证。请检查以下示例
<div ng-app="myapp">
<div ng-controller="comparectrl">
<div ng-form="testform">
<input type="text" id="startdate" name="startdate" ng-model="StartDate" placeholder="StartDate" />
<input type="text" id="enddate" name="enddate" ng-model="EndDate" compareto="#startdate" compare placeholder="EndDate" />
<button ng-click="change()">Change</button>
<br />
<span ng-show="testform.enddate.$error.compare" >Please enter proper date.</span>
</div>
</div>
</div>
var app = angular.module("myapp", []);
app.directive("compare", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elem, attrs, ctrl) {
elem.on("change", function () {
console.log("end date on change event called");
scope.$apply(dovalidation);
});
angular.element(attrs.compareto).on("change", function () {
console.log("start date on change event called");
scope.$apply(dovalidation);
});
function dovalidation() {
var value1 = new Date(angular.element(attrs.compareto).val());
var value2 = new Date(elem.val());
if (value1 > value2) {
ctrl.$setValidity("compare", false);
}
else {
ctrl.$setValidity("compare", true);
}
}
}
};
});
app.controller("comparectrl", function ($scope)
{
$scope.StartDate = "01/01/2012";
$scope.EndDate = "01/01/2013";
$scope.change = function () {
$scope.StartDate = "01/01/2014";
angular.element("#startdate").triggerHandler("change");
}
});