Search code examples
angularjsangularjs-scoperefactoringmomentjsangular-moment

Refactor code to one function for momentjs


I have 2 functions prev() and next() which has almost the same code.

Is there a way that I can combine the 2 functions into one function?

<button id="prev-search-button" ng-click="prev()"><</button>  
<button id="next-search-button" ng-click="next()">></button> 

$scope.prev = function(){ 
  var search = $scope.inputDate ? $scope.inputDate: moment() ;  
  $scope.day = moment(search).subtract(1, 'days').format('DD'); 
  $scope.month=moment(search).subtract(1, 'days').format('MM'); 
};

$scope.next = function(){
  var search = $scope.inputDate ? $scope.inputDate: moment();  
  $scope.day = moment(search).add(1, 'days').format('DD');
  $scope.month = moment(search).add(1, 'days').format('MM'); 
};

I tried the following but does not work

<button id="prev-search-button" ng-click="prevAdd(subtract)"><</button> 
<button id="prev-search-button" ng-click="prevAdd(add)"><</button>  

$scope.prevAdd = function(arg){  
  var search = $scope.inputDate ? $scope.inputDate: moment() ;  
  $scope.day = moment(search).arg(1, 'days').format('DD'); 
  $scope.month=moment(search).arg(1, 'days').format('MM'); 
};

Solution

  • First: ng-click="prevAdd(subtract)", ng-click="prevAdd(add)" are wrong, pass the argument as string or integer like ng-click="prevAdd('subtract')", ng-click="prevAdd('add')"

    Second: There is no method arg in moment(search).arg, it have only add and subtract. So the following statement is wrong:

    $scope.day = moment(search).arg(1, 'days').format('DD'); 
    $scope.month=moment(search).arg(1, 'days').format('MM');
    

    It should be written as:

      if(arg === 'add') {
         $scope.day = moment(search).add(1, 'days').format('DD'); 
         $scope.month=moment(search).add(1, 'days').format('MM');
      } 
      if(arg === 'subtract') {
         $scope.day = moment(search).subtract(1, 'days').format('DD'); 
         $scope.month=moment(search).subtract(1, 'days').format('MM');
      }  
    

    Please use the following final modified code:

    <button id="prev-search-button" ng-click="prevAdd('subtract')"><</button> 
    <button id="prev-search-button" ng-click="prevAdd('add')"><</button>  
    
    $scope.prevAdd = function(arg){  
      var search = $scope.inputDate ? $scope.inputDate: moment() ; 
      if(arg === 'add') {
         $scope.day = moment(search).add(1, 'days').format('DD'); 
         $scope.month=moment(search).add(1, 'days').format('MM');
      } 
      if(arg === 'subtract') {
         $scope.day = moment(search).subtract(1, 'days').format('DD'); 
         $scope.month=moment(search).subtract(1, 'days').format('MM');
      }  
    };