我使用bootstrap-datepicker来选择一系列天数。我尝试将它放在Angular指令中,并期望在更改日期时更新父作用域值,并且日期格式必须在整周(2015年4月20日 - 2015年4月26日)
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');
}
);
}
};
}]);
查看:
<input week-date-picker ng-model="fixtureDate" minviewmode="0" format="MM-yyyy" class="form-control" week="true" style="width:200px" />
答案 0 :(得分:1)
我已经完成了一个带回调的版本(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});
});
在指令中注意这一点;
scope: {changeDate: "&"},
的index.html
$scope.fixtureDate = {
startDate: startDate,
endDate: endDate
};
$scope.updateFixtures = function(startDate, endDate) {
$scope.fixtureDate.startDate = startDate;
$scope.fixtureDate.endDate = endDate;
};
答案 1 :(得分:0)
您应该将html更改为
<input week-date-picker ng-model="fixtureDate" minviewmode="0" format="MM-yyyy" class="form-control" week="true" style="width:200px" />
您的代码中没有名为dt
的变量。您要更改的变量称为fixtureDate
。