Reputation: 3437
I use bootstrap-datepicker for its ability to select a range of days. I try to put it in Angular directive and expect to update the parent scope value when the date changed, and the date format must be in the whole week (20-04-2015 - 26-04-2015)
var app = angular.module('angular.controls.weekDatePicker', [])
app.directive('weekDatePicker', ['$filter', '$parse', function ($filter, $parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
var ngModelParseFn = $parse(attrs.ngModel);
element.datepicker({
minViewMode: parseInt(attrs.minviewmode),
format: attrs.format,
language: "vi"
}).on('changeDate', function (e) {
scope.$apply(function () {
console.log(scope.$parent);
if (attrs.week == 'true') {
}
else {
// code
}
});
});
element.datepicker('update', new Date()); //reset to now
if (attrs.week == 'true') {
scope.$watch(function () {
return ngModelCtrl.$modelValue;
}, function (newValue) {
var date = element.data().datepicker.viewDate;
var startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
var endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
startDate = $filter('date')(startDate, 'dd-MM-yyyy');
endDate = $filter('date')(endDate, 'dd-MM-yyyy');
console.log(scope.$parent.fixtureDate); //fail to get parent scope value ?
var dateText = startDate + ' - ' + endDate;
ngModelParseFn.assign(scope, dateText);
});
}
scope.$on("$destroy",
function handleDestroyEvent() {
element.datepicker('remove');
}
);
}
};
}]);
View:
<input week-date-picker ng-model="fixtureDate" minviewmode="0" format="MM-yyyy" class="form-control" week="true" style="width:200px" />
Upvotes: 0
Views: 158
Reputation: 12813
I've done a version with a callback (Plunker).
JS
element.datepicker({
minViewMode: parseInt(attrs.minviewmode),
format: attrs.format,
language: "vi"
}).on('changeDate', function(e) {
var date = e.date;
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1); // 0 = january
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var startDate = firstDay.getDate() + '-' + (firstDay.getMonth() + 1) + '-' + firstDay.getFullYear();
var endDate = lastDay.getDate() + '-' + (lastDay.getMonth() + 1) + '-' + lastDay.getFullYear();
scope.changeDate({startDate: startDate, endDate: endDate});
});
Note this in the directive;
scope: {changeDate: "&"},
index.html
$scope.fixtureDate = {
startDate: startDate,
endDate: endDate
};
$scope.updateFixtures = function(startDate, endDate) {
$scope.fixtureDate.startDate = startDate;
$scope.fixtureDate.endDate = endDate;
};
Upvotes: 1
Reputation: 1519
You should change the html to
<input week-date-picker ng-model="fixtureDate" minviewmode="0" format="MM-yyyy" class="form-control" week="true" style="width:200px" />
You have no variable called dt
in your code. The variable that you want to change is called fixtureDate
.
Upvotes: 0