Plunker link of my usecase.
I am using Eternicode's Bootstrap Datepicker in my app. I have created a datepicker directive and same is used in Angular form.
Datepicker directive :
angular.module('MyApp', [])
.directive('myDatePicker', function($compile) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
$(element[0]).datepicker({
autoclose: true,
format: "dd/mm/yyyy"
});
$(element[0]).datepicker().on("change", function(e) {
scope.$apply(function() {
ngModelCtrl.$setViewValue(element.val());
});
});
}
};
});
When the Angular form is initially loaded, following are its properties:
$pristine : false
$dirty : true
When i watch
the form model
and print them on console, i understood form model had property that was set by datepicker and this is how it looks :
On same Plunker link , if i comment date section in form following are its properties:
$pristine : true
$dirty : false
This is how form model
looks now :
How do i keep my form model free from being corrupted, which is causing problems by setting $pristine to false and $dirty to true, despite of using Date directive ?
PS : This is the abstraction of the bigger use-case that is in our current application.
Thanks in advance.
I have investigated you code and observed that, you should write you following code in compile function of directive.
$(element[0]).datepicker({
autoclose: true,
format: "dd/mm/yyyy"
});
it will resolve your problem.
so your directive looks like as follow :
.directive('myDatePicker', function($compile) {
return {
restrict: 'A',
require: 'ngModel',
compile: function(scope, element, attrs) {
$(element[0]).datepicker({
autoclose: true,
format: "dd/mm/yyyy"
});
},
link: function(scope, element, attrs, ngModelCtrl) {
$(element[0]).datepicker().on("change", function(e) {
scope.$apply(function() {
ngModelCtrl.$setViewValue(element.val());
});
});
}
};
The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often.