2
我创造了这个指令:为什么手动将控件设置为Angular的原始形式时,表单会被标记为脏?
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()
,但是此操作没有通过表单控件oller,因为form.$dirty
设置为true
,但是当我检查form.StartDate.$dirty
时,它设置为false
。
这怎么可能,我怎么能确保/强制form
看到StartDate
不是脏?
你的答案提供了解决方法;它并不回答你的问题。我将这称为Angular中的一个错误(与1.4.8相同的问题)。下面是一个简单的演示问题的普朗克:https://plnkr.co/edit/6noEtj6vbMkqxiKK6Yp7?p=preview – Eccentropy