回答

2

花了一些時間試圖找到正確的方式來獲得這個,並在閱讀datepicker指令和控制器的源代碼後,我找不到一個非骯髒的方式獲取當前月份,所以這是一個非常hacky方法來做到這一點。

警告,角UI引導的未來版本可能打破這種方法

您將需要使用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; 
}) 

由於日期選擇器控制器不守$scope內當前選定的日期,它保持它在一個閉包變量中,當調用函數move時,我找到您的唯一方法是獲得所選月份的this對象。只要您點擊上一個和下一個月的圖標,就會調用move

這裏有一個plunkr證明這個裝飾的用法:http://plnkr.co/edit/iWJWjM8nCsh5TMupNioo?p=preview

+0

非常感謝!這絕對是完整的答案!))超出我的預期)) – Marik

+0

既然你已經研究過這個話題,你能幫我解決另一個datepicker功能擴展相關的問題嗎? http://stackoverflow.com/q/32676310/601726 – Marik

+0

完成!希望能幫助到你! – yvesmancera

1

您應該使用ng-model將選定的值分配給一個變量。如果您使用原始範圍變量,則可以隨時訪問Date對象。例如: -

<input ng-model="selectedDate" other-datepicker-directives /> 

然後在你的控制器中,selectedDate值是Date對象,以您可以使用普通的日期屬性;像.getMonth()。如果您隨後使用手錶,則可以使用當前選定的月份始終設置本地變量!

所以,在你的控制器:

$scope.$watch(function() { return $scope.selectedDate }, function() 
{ 
    // bail out if no selected date 
    if (!angular.isDefined($scope.selectedDate)) return; 

    $scope.selectedMonth = $scope.selectedDate.getMonth(); 
}); 

現在只要$ scope.selectedDate得到改變,$ scope.selectedMonth將被更新。這意味着你可以在你的HTML視圖中顯示選定月份,像這樣:

< SPAN>選擇的月份:{{selectedMonth}} </SPAN>

希望幫助!

+0

時已選定的日期這個工作,這個問題問選擇日期之前如何讓開放一個月。 – yvesmancera

+0

@yvesmancera是非常正確的。我試圖獲取顯示的月份(呈現的日期選擇器模板的一部分),而不是選定的日期月份。 – Marik

+0

啊好點 - 我錯過了。看起來不像是可以輕鬆獲得的東西......在日期選擇器視圖中有一個範圍變量「title」,在日視圖模式下有月份...類似於: angular.element(「 .yourElementSelectorWithDatePickerDirective 「)。控制器(」 的DatePicker「)。這將爲您提供DatePicker的控制器,然後可以訪問子指令的標題(Day picker)。 –

相關問題