2016-12-27 82 views
2

我已經創建了有一個「選項」一個簡單的日期選擇器指令。AngularJS - 如何刷新指令範圍

於是我開始用日期選擇器一組選項,然後業務邏輯的,因爲我改變了這些選項,但這不是被刷新。

在這個例子中,我需要去的「結束日期」相同的日期作爲「的startDate」的日期選擇開始日期進行更新。

這裏是我的代碼:

指令:

function datepicker() { 
    return { 
     restrict: "A", 
     scope: { 
      options : '=' 
     }, 
     link: function(scope, element, attrs) { 

      var opts = scope.options || {}; 

      element.datepicker({ 
       keyboardNavigation: false, 
       forceParse: false, 
       autoclose: true, 
       useCurrent: true, 
       format: opts.format || 'dd/mm/yyyy', 
       startDate : opts.startDate || '' 
      }); 
     } 
    }; 
} 

控制器:

$scope.evaluation = {}; 

$scope.startDatepickerOptions = { 
    startDate : new Date() 
}; 

$scope.endDatepickerOptions = { 
    startDate : new Date() 
}; 

$scope.$watch('evaluation.startDate', function(newValue) { 
    $scope.endDatepickerOptions.startDate = newValue; 
}); 

查看:

<input type="text" ng-model="evaluation.startDate" name="startDate" datepicker options="startDatepickerOptions"/> 

<input type="text" ng-model="evaluation.endDate" name="endDate" datepicker options="endDatepickerOptions"/> 
+0

你吃過看看這個[SO問題](http://stackoverflow.com/questions/20 856824 /角指令-刷新上參數變化)? –

+0

不適合我 –

回答

1

所以這裏的解決方案:

我需要在指令鏈接功能上添加一個平等觀察器。到目前爲止,由於日期/串的問題,我已經實現了moment.js library

下面是最終代碼:

指令(鏈接功能)

link: function(scope, element, attrs) { 

    var opts = scope.options || {}; 

    element.datepicker({ 
     keyboardNavigation: false, 
     forceParse: false, 
     autoclose: true, 
     useCurrent: true, 
     format: opts.format || 'dd/mm/yyyy', 
     startDate : opts.startDate || '' 
    }); 

    scope.$watch('options.startDate', function(newValue) { 
     if(newValue) { 
      element.datepicker('setStartDate', newValue); 
      element.datepicker('setDate', ""); 
     } 
    }); 
} 

控制器

$scope.startDatepickerOptions = { 
    startDate : moment().toDate() 
}; 

$scope.endDatepickerOptions = { 
    startDate : moment().toDate() 
}; 

$scope.$watch('evaluation.startDate', function(newValue) { 
    if(newValue) 
     $scope.endDatepickerOptions['startDate'] = moment(newValue, "DD-MM-YYYY").toDate(); 
});