Angular bootstrap datepicker date format does not format ng-model value

后端 未结 13 1351
借酒劲吻你
借酒劲吻你 2020-12-01 04:24

I am using bootstrap date-picker in my angular application. However when I select a date from that date-picker underlying ng-model that I have bind gets updated I want that

13条回答
  •  粉色の甜心
    2020-12-01 04:41

    The datepicker (and datepicker-popup) directive requires that the ng-model be a Date object. This is documented here.

    If you want ng-model to be a string in specific format, you should create a wrapper directive. Here is an example (Plunker):

    (function () {
        'use strict';
    
        angular
            .module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
            .controller('MyController', MyController)
            .directive('myDatepicker', myDatepickerDirective);
    
        MyController.$inject = ['$scope'];
    
        function MyController ($scope) {
          $scope.dateFormat = 'dd MMMM yyyy';
          $scope.myDate = '30 Jun 2017';
        }
    
        myDatepickerDirective.$inject = ['uibDateParser', '$filter'];
    
        function myDatepickerDirective (uibDateParser, $filter) {
            return {
                restrict: 'E',
                scope: {
                    name: '@',
                    dateFormat: '@',
                    ngModel: '='
                },
                required: 'ngModel',
                link: function (scope) {
    
                    var isString = angular.isString(scope.ngModel) && scope.dateFormat;
    
                    if (isString) {
                        scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
                    } else {
                        scope.internalModel = scope.ngModel;
                    }
    
                    scope.open = function (event) {
                        event.preventDefault();
                        event.stopPropagation();
                        scope.isOpen = true;
                    };
    
                    scope.change = function () {
                        if (isString) {
                            scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
                        } else {
                            scope.ngModel = scope.internalModel;
                        }
                    };
    
                },
                template: [
                    '
    ', '', '', '', '', '
    ' ].join('') } } })();
    
    
    
      
        
        
        
        
        
        
      
    
      
        

    Date format: {{dateFormat}}

    Value: {{myDate}}

提交回复
热议问题