2014-02-14 33 views
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不是脏?

回答

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); 
      }) 
     } 
    } 
}]) 
+0

你的答案提供了解决方法;它并不回答你的问题。我将这称为Angular中的一个错误(与1.4.8相同的问题)。下面是一个简单的演示问题的普朗克:https://plnkr.co/edit/6noEtj6vbMkqxiKK6Yp7?p=preview – Eccentropy

相关问题