我创建了一个样本日期范围验证指令。
当开始日期大于结束日期时,我们必须抛出验证错误。如果我通过更新开始日期文本框中的值来更改开始日期的值,则验证正常工作。但是当我使用controller事件更改开始日期的值时,验证不会触发。请查看以下示例
<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");
}
});
答案 0 :(得分:0)
我有一个类似的问题。通过获取表单对象(代码中的testform)的副本进行修复,然后在模型更改后将其分配回去。我的表单中有一个ng-repeat
。在从控制器更改ng-repeat
模型后,我的表单模型被清空了。因此,我保留了表单模型的副本并重新分配了它。
<form name='testform'>
<input name='fullname' ng-model='fullName'/>
</form>
$scope.change = function(){
var copyTestForm = $scope.testform;
$scope.fullName = 'Elon Musk';
$scope.testform = copyTestForm;
}