Detect selected month in Angular custom upload downloads

I am using Angular UI Bootstrap datepicker in day mode for my project. How can I get the current open month that selected a new date?

+4
source share
2 answers

After spending some time trying to find the right way to get this, and reading the datepicker directive and the source code of the controller, I could not find a dirty way to get the current month, so here is a very hacky way to do this.

Warning, future versions of Angular -UI Bootstrap may violate this approach

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 original compile function
      var directiveCompile = directive.compile;

      //overwrite the original compile function
      directive.compile = function(tElement, tAttrs) {
        // call the directive compile with apply to send the original 'this' and arguments to it
        var link = directiveCompile.apply(this, arguments);

        //here 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, , , , , this, move. move , .

plunkr : http://plnkr.co/edit/iWJWjM8nCsh5TMupNioo?p=preview

+2

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>

, !

+1

Source: https://habr.com/ru/post/1608056/


All Articles