我尝试将引导日期选择器从eternicode转换为angularjs指令,并允许选择周模式。问题是视图中的值{{var1}}没有反映到我在Directive上设置的自定义值
weekDatePicker指令:
var app = angular.module('angular.controls', [])
app.directive('weekDatePicker', ['$filter','$parse', function ($filter, $parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
console.log('start');
element.datepicker({
//minViewMode: 1,
//format: "MM-yyyy"
}).on('changeDate', function (e) {
scope.$apply(function () {
var date = e.date;// element.datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
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');
dateText = startDate + ' - ' + endDate;
e.date = dateText;
//console.log(e.date);
ngModelCtrl.$setViewValue(dateText); //>> no change from view
console.log(ngModelCtrl);
});
});
}
};
}]);
您可以在jsFiddle
看到整个代码查看:<input week-date-picker ng-model="var1" class="form-control" />
{{var1}}
&gt;&gt;为什么它没有从指令中获取自定义值?
答案 0 :(得分:1)
我已经分了你fiddle
var app = angular.module('angular.controls', [])
app.directive('weekDatePicker', ['$filter','$parse', function ($filter, $parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
console.log('start');
var ngModelParseFn = $parse(attrs.ngModel);
element.datepicker({
//minViewMode: 1,
//format: "MM-yyyy",
// language: "vi"
})
scope.$watch(function () {
return ngModelCtrl.$modelValue;
}, function (newValue) {
var date = element.data().datepicker.viewDate;
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
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');
dateText = startDate + ' - ' + endDate;
ngModelParseFn.assign(scope, dateText);
});
}
};
}]);
希望这就是你想要的。