angularjs - 在 Angular 中动态设置 ngModelOptions

标签 angularjs

我有以下片段:

<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}}

但是,更改时区永远不会更新到达(看来绑定(bind)不适用于 nd-model-options )。当时区更改时,我可以通过什么方式强制刷新字段?

编辑

fiddle :https://jsfiddle.net/10nfqow9/

最佳答案

创建另一个具有高优先级(高于 ng-model/ng-model-option's)的指令(属性类型),用于监视选项对象的更改并触发重新编译。我很抱歉缺乏细节,我正在打电话:)

编辑:
看起来有一个名为 kcd-recompile 的指令这正是我所描述的。这是一个有效的plnkr ,还有一些额外的好处,可以将美国时区的 DST 考虑在内。

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

关于angularjs - 在 Angular 中动态设置 ngModelOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806912/

相关文章:

javascript - 如果一个 promise 失败,$q.all() 不会调用失败处理程序

javascript - 单击更改动态按钮的 CSS

javascript - 使用 Angular js 重置表首选项

css - 带有自定义主题的 bootstrap 3 datepicker - 看起来很讨厌

javascript - ng-repeat 破坏指令模型绑定(bind)

javascript - AngularJS格式化数字计算

javascript - 在将图像发送到 Cloudinary 之前对其进行 Base64 压缩

javascript - 带有 Kendo UI 的 AngularJS 每个都给出 "TypeError: Object [object Object] has no method ''”

javascript - 使用 angularjs 1.4 提交验证不起作用

angularjs - AngularStrap bs-select 不更新 ng-model