2013-04-21 20 views
2

我想在表單上實現開始和結束日期,但也允許用戶從下拉列表中選擇一堆預設的日期範圍。如果用戶從下拉列表中選擇一個值,則會填入開始日期和結束日期字段。如果用戶編輯其中一個字段,則下拉列表將自己設置爲「自定義」選擇。

我的「天真」實現方式如下,但顯然,無論用戶或控制器是否更改了字段,所有手錶都會觸發。我怎樣才能設置我的手錶,以便這可能工作?

HTML

<div ng-controller="ExportCtrl"> 
    <select ng-model="dateRange" ng-options="d.name for d in dateRanges"></select>          
    <input type="text" ng-model="startDate" /> 
    <input type="text" ng-model="endDate" /> 
</div> 

JS

module.controller("ExportCtrl", function ($scope) { 
    $scope.dateRanges = [ 
      { name: 'Custom', startDate: null, endDate: null }, 
      { name: 'Today', startDate: moment().startOf('day'), endDate: moment().endOf('day') }, 
      { name: 'Yesterday', startDate: moment().subtract('day', 1).startOf('day'), endDate: moment().subtract('day', 1).endOf('day') }, 
      { name: 'Last 3 days', startDate: moment().subtract('day', 2).startOf('day'), endDate: moment().endOf('day') }, 
      { name: 'Last 7 days', startDate: moment().subtract('day', 6).startOf('day'), endDate: moment().endOf('day') }, 
      { name: 'Last 30 days', startDate: moment().subtract('day', 29).startOf('day'), endDate: moment().endOf('day') }, 
      { name: 'Month to Date', startDate: moment().startOf('month'), endDate: moment().endOf('day') }, 
      { name: 'Last month', startDate: moment().subtract('month', 1).startOf('month'), endDate: moment().subtract('month', 1).endOf('month') }, 
      { name: 'Last 3 months', startDate: moment().subtract('month', 3).startOf('day'), endDate: moment().endOf('day') } 
    ]; 
    $scope.dateRange = $scope.dateRanges[1]; 

    $scope.$watch('dateRange', function (newValue, oldValue) { 
     if (oldValue === newValue) { 
      return; 
     } 
     $scope.dateRange = newValue; 
     $scope.startDate = $scope.dateRange.startDate; 
     $scope.endDate = $scope.dateRange.endDate; 
    }); 

    $scope.$watch('startDate', function (newValue, oldValue) { 
     if (oldValue === newValue) 
      return; 
     $scope.dateRange = $scope.dateRanges[0]; 
     $scope.startDate = newValue; 
    }); 

    $scope.$watch('endDate', function (newValue, oldValue) { 
     if (oldValue === newValue) 
      return; 
     $scope.dateRange = $scope.dateRanges[0]; 
     $scope.endDate = newValue; 
    }); 
}); 
+0

希望有人對此有一些經驗!我想設置我的$範圍值,但我沒有更新daterangepicker ... – tdhulster 2013-04-26 12:30:58

回答

1

你觀察家導致循環依賴。你應該同時觀看它們,並在那裏定義你的邏輯。

$scope.$watch(function() { return $scope.dateRange + ',' + $scope.startDate.getTime() + ',' + $scope.endDate.getTime(); }, function (newValue, oldValue) { 
    //recover new values of all three variables from newValue.split(',') 
    //if all three values satisfy the constraints defined in $scope.dateRanges, return 
    //if dateRange changes, change startDate and endDate 
    //if startDate or endDate changes, change dateRange 
}); 
相關問題