为什么在Angular中手动将控件设置为pristine时,我的表单被标记为脏?

时间:2014-02-14 15:01:58

标签: javascript angularjs angularjs-directive

我创建了这个指令:

app.directive("date", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attributes, controller) {          
            scope.$watch(function () {
                return controller.$modelValue;
            },
            function (newVal, oldVal) {
                if (newVal !== oldVal && newVal) {
                    var format = attributes.date || "dd-MM-yyyy";
                    var parsedDate = new Date(newVal);

                    parsedDate = $filter('date')(newVal, format);

                    controller.$setViewValue(parsedDate);
                    controller.$setPristine();
                    controller.$render();
                }
            });
        }
    }
}])

我这个指令是这样的:

<form name='myForm'>
    Date: <input type="text" data-ng-model="contract.StartDate" name="StartDate" date />
</form>

在我的范围内,我有一个确定保存按钮状态的函数:

scope.canSave = function () {
    return scope.contractForm.$valid && scope.contractForm.$dirty;
}

正如您在date指令的代码段中看到的那样,我设置了controller.$setPristine(),但是表单控制器看不到此操作,因为form.$dirty设置为{{ 1}},但是当我选中true时,它会设置为form.StartDate.$dirty

这怎么可能?如何确保false看到form 脏?

1 个答案:

答案 0 :(得分:0)

我终于找到了解析器和格式化程序形式的解决方案:

app.directive("date", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attributes, controller) {
            controller.$parsers.unshift(function (value) {
                if (!value) {
                    return;
                }

                var format = attributes.date || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })

            controller.$formatters.unshift(function (value) {
                if (!value) return;

                var format = attributes.date || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })
        }
    }
}])
相关问题