将代码重构为 momentjs 的一个函数

Refactor code to one function for momentjs

我有 2 个函数 prev() 和 next(),它们的代码几乎相同。

有什么方法可以将这两个函数合并为一个函数吗?

<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'); 
};

我尝试了以下但不起作用

<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'); 
};

首先: ng-click="prevAdd(subtract)"ng-click="prevAdd(add)" 是错误的,将参数作为字符串或整数传递,如 ng-click="prevAdd('subtract')"ng-click="prevAdd('add')"

其二:moment(search).arg中没有方法arg,只有addsubtract。所以下面的说法是错误的:

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

应该写成:

  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');
  }  
};