【问题标题】:datepicker inside a modal not working模态中的日期选择器不起作用
【发布时间】:2013-10-25 01:43:06
【问题描述】:

我正在尝试使用 ui-bootstrap 组件在模式中创建日期选择器。日期选择器必须发回格式化为 unix 时间戳的日期。

  1. 如果日期选择器不在模态框内(= 选择日期时时间戳更新),这可以正常工作:http://plnkr.co/edit/xQFmVgJojiq6aG9U8f4H?p=preview

  2. 然后,我将指令放入模态:http://plnkr.co/edit/9zHQQPGAcomT5Vha33j3?p=preview

这里是控制器:

.controller('MyCtrl', [ '$scope', '$modal', function ($scope, $modal) {
    $scope.open = function () {
        var modalInstance = $modal.open({
            templateUrl: 'tplModal.html',
            controller: 'MyModalCtrl'
        });
    };
}])
.controller('MyModalCtrl', [ '$scope', '$modalInstance', function ($scope, $modalInstance) {
    $scope.required= {};
    $scope.disabled = function(date, mode) {
        return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
    };
    $scope.minDate = new Date();
    $scope.$watch('dt', function() { 
        if ($scope.dt) $scope.required.timestamp = Math.floor($scope.dt.getTime() / 1000); 
        console.log('timestamp: ', $scope.required.timestamp, '/ dt: ', $scope.dt);
    });
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);

和模态的html模板:

<div class="modal-body">
    <div ng-model="dt">
        <datepicker min="minDate" show-weeks="false"></datepciker>
    </div>
    <div>
        dt <span class="uneditable-input span2">{{dt | date:'dd.MM.yyyy' }}</span>
        dt <span class="uneditable-input span2">{{ dt }}</span>
        timestamp <span class="uneditable-input span2">{{ required.timestamp }}</span>
    </div>
</div>

在第二个版本中,日期更改时时间戳不会更新(就像 $watch 不工作一样)。

你知道怎么做吗?

【问题讨论】:

  • 如果我不得不猜测您遇到了范围问题;其中模态创建控制器的子范围。我使用 ng-include 遇到了这个问题。我看不到你的 dt 是在哪里定义的;但我的解决方案 [在我的情况下] 是将我的“简单值”放入控制器的对象中,以便在子范围内可以访问它。 [简单的属性没有被继承;但对象是]。

标签: angularjs angular-ui-bootstrap


【解决方案1】:

您需要在ng-model 表达式中使用著名的“点”,因为$modal 正在为窗口内容创建一个trasclusion 范围。换句话说,在您的控制器和模态内容之间创建了一个范围。

无论如何,在ng-model 表达式中使用点(这是最佳实践)可以为您解决问题:

<div ng-model="dt.value">
  <datepicker min="minDate" show-weeks="false"></datepciker>
</div>

在 JavaScript 中:

$scope.dt = {};
$scope.$watch('dt.value', function(newValue) { 
  if (newValue) $scope.required.timestamp = Math.floor(newValue.getTime() / 1000); 
  console.log('timestamp: ', $scope.required.timestamp, '/ dt: ', newValue);
});

在这里工作:http://plnkr.co/edit/Adst8I8S0e0DLcVnhpLq?p=preview

【讨论】:

    【解决方案2】:

    您必须应用与 timestamp 相同的技巧,并将其放入范围内的对象中,就像我对 here 所做的那样。

    $scope.picker = {
      dt: new Date(),
      timestamp: ''
    };
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2014-11-25
      相关资源
      最近更新 更多