我在日模式下使用
Angular UI Bootstrap日期选择器为我的项目.如果选择新日期,我怎样才能获得当前开放的月份?
解决方法
花了一些时间试图找到正确的方法来获得这个,并在阅读datepicker指令和控制器的源代码后,我找不到一个非脏的方式获得当前月份,所以这是一个非常hacky方式来做到这一点.
@H_502_12@
警告,未来版本的Angular-UI Bootstrap可能会破坏这种方法@H_502_12@
你需要使用AngularJS decorators.这是您需要的代码:@H_502_12@
@H_502_12@
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:@H_502_12@
@H_502_12@
$scope.$on('datepicker.monthChanged',function(event,newVal) { $scope.currentMonth = newVal; })
由于datepicker控制器没有将当前所选日期保留在$scope中,因此它将其保存在一个闭包变量中,当调用函数move时,我发现你可以获得所选月份的唯一方法是在this对象中.只要您单击上一个和下个月的图标,就会调用move.@H_502_12@
这是一个使用这个装饰器的傻瓜:http://plnkr.co/edit/iWJWjM8nCsh5TMupNioo?p=preview@H_502_12@