1

我创建了一个示例日期范围验证指令。

当开始日期大于结束日期时,我们必须抛出验证错误。如果我通过更新开始日期文本框中的值来更改开始日期的值,则验证工作正常。但是当我使用控制器事件更改开始日期的值时不会触发验证。请检查以下示例

<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");
    }
});
4

1 回答 1

0

我有一个类似的问题。通过获取表单对象(代码中的测试表单)的副本来修复它,然后在模型更改后将其分配回来。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;
}
于 2019-07-05T07:54:55.427 回答