My Directive with name of datePicker Is On the Input Element, that gets gregorian date from model And converts it to persian date for the end user. with changing date from datePicker(here it is jalali(persian date picker)),it is nessaccery to be converted to gregorian and updates the model.
- I am not sure from binding type that i used.
- $watch function dont work for me ,it works when page loaded first time.
- what is happening for ngModel and dateDirVal attributes in isolated scope?
- the value of ngModelCtrl.$viewValue in gregorianToJalali function equals to NaN. Why?
my HTML :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/jalali/theme.css" rel="stylesheet" />
<script src="Scripts/jalali/jalali.js"></script>
<script src="Scripts/jalali/calendar.js"></script>
<script src="Scripts/jalali/calendar-setup.js"></script>
<script src="Scripts/jalali/calendar-fa.js"></script>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/directive.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<input ng-model="dateValue1" date id="id1" />
</div>
</body>
</html>
and My Directive :
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
var date = new Date('2014', '06', '03');
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 1);
$scope.dateValue1 = new Date(newdate);
})
.directive('date', function ($compile) {
return {
restrict: 'A',
require: ['date', '^ngModel'],
scope: {
dateDirVal: "=ngModel"
},
controller: function ($scope) {
},
compile: function (element, attr, linker) {
return {
post: function postLink($scope, element, attrs, ctrls) {
var myCtrl = ctrls[0], ngModelCtrl = ctrls[1];
var inputId = element.attr('id').toString();
gregorianToJalali();
function gregorianToJalali() {
var val = ngModelCtrl.$viewValue;
if ($scope.dateDirVal) {
var inputValue = $scope.dateDirVal;
var gDate = new Date(inputValue);
var gY = gDate.getFullYear();
var gM = gDate.getMonth();
var gD = gDate.getDate();
var value = JalaliDate.gregorianToJalali(gY, gM, gD);
var jalali = value[0].toString() + "/" + value[1].toString() + "/" + value[2].toString();
$scope.dateDirVal = jalali;
}
}
Calendar.setup({
inputField: inputId,
ifFormat: '%Y/%m/%d',
dateType: 'jalali'
});
element.bind("blur", function (e) {
var jDate = element.val().split('/');
var value = JalaliDate.jalaliToGregorian(jDate[0], jDate[1], jDate[2]);
var gDate = new Date(value[0], value[1], value[2]);
ngModelCtrl.$setViewValue(gDate);
$scope.dateDirVal = value;
});
$scope.$watch("dateDirVal", function (newValue, OldValue, scope) {
if (newValue) {
alert(JSON.stringify(newValue));
}
//ngModelCtrl.$setViewValue(gDate);
//$scope.dateDirVal = value;
});
}
}
}
};
});