2016-03-04 68 views
4

我有下面的代碼片段:動態設置ngModelOptions在角

<input type="date" ng-model="arrival" ng-model-options="{timezone: 'PST'}" /> 
<input type="time" ng-model="arrival" ng-model-options="{timezone: 'PST'}" /> 
{{arrival}} 

可以正常工作(日期顯示,從PST轉換UTC時間)。現在我努力使「PST」選項動態:

<select ng-model="timezone> 
    <option value="PST">PST</option> 
    <option value="EST">EST</option> 
</select> 
<input type="date" ng-model="arrival" ng-model-options="{timezone: timezone}" /> 
<input type="time" ng-model="arrival" ng-model-options="{timezone: timezone}" /> 
{{arrival}} 

但是,更改時區從不更新的到來(似乎綁定不nd-model-options工作)。任何方式我可以強制時區更改時刷新字段?

編輯

小提琴:https://jsfiddle.net/10nfqow9/

+0

嘗試具有以ng-模型選項的對象,是這樣的: 'NG-模型選項= 「選項」' 和 '$ scope.options = {timezone:$ scope.timezone}' –

+0

@NMittal沒有什麼區別。 –

回答

1

具有高優先級創建另一個指令(屬性類型)(高於NG-模型/ NG-模式選項的),其手錶的選擇對象的變化和觸發重新編譯。我很抱歉缺乏具體細節,我在打電話:)

編輯: 看起來像有一個指令kcd-recompile,正是我所描述的。這裏有一個工作plnkr,在美國時區用於考慮夏令時的一些額外好處。

HTML:

<div kcd-recompile="data.timezone"> 
    <div> 
    <select ng-model="data.timezone" ng-options="x.offset as x.name for x in timezones"> 
    </select> 
    </div> 
    <div> 
    <input type="date" ng-model="data.arrival" ng-model-options="{timezone: data.timezone}" /> 
    </div> 
    <div> 
    <input type="time" ng-model="data.arrival" ng-model-options="{timezone: data.timezone}" /> 
    </div> 
</div> 

和JS:

Date.prototype.stdTimezoneOffset = function() { 
    var jan = new Date(this.getFullYear(), 0, 1); 
    var jul = new Date(this.getFullYear(), 6, 1); 
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()); 
} 

Date.prototype.dst = function() { 
    return this.getTimezoneOffset() < this.stdTimezoneOffset(); 
} 

angular.module('DemoApp', ['kcd.directives']); 
angular.module('DemoApp') 
.controller('DemoCtrl', ['$scope', function($scope) { 
    var now = new Date(), 
     isDst = now.dst(); 

    $scope.data ={ 
     arrival: now, 
     timezone: null 
    }; 
    $scope.timezones = [ 
     { 
     name: 'PST', 
     offset: isDst ? '-0700' : '-0800' 
     }, 
     { 
     name: 'EST', 
     offset: isDst ? '-0400' : '-0500' 
     } 
    ]; 
    }] 
);