我在白天模式下为我的项目使用Angular UI Bootstrap日期选择器。如何在选择新日期之前获得当前开放的月份?
[花了一些时间试图找到正确的方法后,并且阅读了datepicker指令和控制器的源代码之后,我找不到获取当前月份的可靠方法,所以这是一种非常笨拙的方法做。
警告,将来的Angular-UI Bootstrap版本可能会破坏此方法
您将需要使用AngularJS decorators。这是您需要的代码:
angular.module('myApp', [
'ui.bootstrap'
])
.config(function($provide) {
$provide.decorator('datepickerDirective', function($delegate) {
var directive = $delegate[0];
//get a copy of the directive's original compile function
var directiveCompile = directive.compile;
//overwrite the original compile function
directive.compile = function(tElement, tAttrs) {
// call the directive's compile with apply to send the original 'this' and arguments to it
var link = directiveCompile.apply(this, arguments);
//here's where the magic starts
return function(scope, element, attrs, ctrls) {
//call the original link
link.apply(this, arguments);
//move is the internal function called when you click
//on the chevrons for previous and next month
var originalMove = scope.move;
scope.move = function(direction) {
originalMove.apply(this, arguments);
//when move is called, the 'this' object contains a 'title' property with the current month!
var currentMonth = this.title;
//emit the event to parent scopes
scope.$emit('datepicker.monthChanged', currentMonth);
}
}
};
return $delegate;
});
})
然后您的控制器可以收听datepicker.monthChanged
:
$scope.$on('datepicker.monthChanged', function(event, newVal) {
$scope.currentMonth = newVal;
})
由于datepicker控制器未将当前选择的日期保留在$scope
内,因此将其保留在闭包变量中,我发现可以获取选择的月份的唯一方法是当函数[ C0]被调用。每当您单击上个月和下个月的图标时,就会调用this
。
这里是一个演示此装饰器用法的小矮人:move
您应使用ng-model将所选值分配给变量。如果您使用原始范围变量,则可以随时访问Date对象。例如:]]
move
然后在您的控制器中,selectedDate值是一个Date对象,您可以访问其正常日期属性;如.getMonth()。如果您随后使用手表,则可以始终将本地变量设置为当前选定的月份!
因此,在您的控制器中:
http://plnkr.co/edit/iWJWjM8nCsh5TMupNioo?p=preview现在,只要更改$ scope.selectedDate,就会更新$ scope.selectedMonth。这意味着您可以在HTML视图中显示选定的月份,如下所示:
所选月份:{{selectedMonth}} span>
希望有帮助!
<input ng-model="selectedDate" other-datepicker-directives />