【问题标题】:need to update the ngModel value on angular-ui bootstrap datepicker需要更新 angular-ui bootstrap datepicker 上的 ngModel 值
【发布时间】:2017-10-15 06:21:35
【问题描述】:

在 NG-UI 引导日历中,我能够正确查看日期格式,但 ngmodel 中的值似乎是日期字符串,例如 Wed Oct 18 2017 00:00:00 GMT-0400 (EDT)。

我尝试更新我的 ngmodel 以保持 2017 年 10 月 18 日的值。但我正面临 $apply 已经在进行中的错误。

<input type="text" class="text-input" id="screeningDateFromSearch" 
       datepicker-popup uib-datepicker-popup="{{format}}" 
       placeholder="mm/dd/yyyy"
       ng-model="searchInput.screeningDateFrom"
       is-open="datesPicker.screeningDateFrom"
       datepicker-options="dateOptions"
       show-button-bar="false" ng-required="true" close-text="Close"
       ng-change="searchScreenings()" />
angular.module('moduleName')
    .directive('datepickerPopup', function (dateFilter) {
        return {
            require: '^ngModel',
            restrict: 'EA',
            link: function (scope, elm, attrs, ctrl) {
                var dateFormat = attrs.uibDatepickerPopup;
                attrs.$observe('datepickerPopup', function (newValue) {
                    if (dateFormat == newValue || !ctrl.$modelValue) return;
                    dateFormat = newValue;
                    ctrl.$modelValue = new Date(ctrl.$setViewValue);
                });

                ctrl.$formatters.unshift(function (modelValue) {
                    if (!dateFormat || !modelValue) return "";
                    var retVal = dateFilter(modelValue).format(dateFormat);
                    return retVal;
                });

                ctrl.$parsers.unshift(function (viewValue) {
                    var date = dateFilter(viewValue, dateFormat);
                    scope.$apply(function (viewValue) {
                        ctrl.$setViewValue(date);
                        ctrl.$render();
                    });
                });

            }
        };
    })

后来尝试使用 $scope.safeApply,但这也不适用于此代码 sn-p 请建议更新值的最佳方法。

【问题讨论】:

  • $setViewValue 方法自动调用摘要循环。为什么你觉得你需要使用$apply
  • 对于uib-datepicker-popup directveng-model 应该设置为Date object 而不是字符串。您的 datepicker-popup 指令正在与 uib-datepicker-popup 指令作斗争。你想用它来完成什么?
  • 我正在尝试将覆盖 ng-model 值更新为 10/18/2017。

标签: angularjs datepicker angular-ui-bootstrap


【解决方案1】:

将此代码添加到ng-change

$scope.searchScreenings = function(){
    var screeningDateFrom =  $filter('date')($scope.searchInput.screeningDateFrom, 'mm/dd/yyyy');
}

别忘了在你的控制器中注入$filter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多