Angular Datatable中的正确日期格式

时间:2015-07-31 07:14:40

标签: javascript angularjs

我有日期格式化问题。我的应用程序中有表格,当我向他们添加内容时,日期格式不正确。现在它看起来像在屏幕上。我想将其格式化为YYYY-MM-DD。有什么帮助,建议吗?

screen from console

appManagementProjects.js

(function() {
'use strict';

angular
    .module('appManagementProjects', [
        'ngMaterial'
    ])
    .controller('ManagementProjectsCtrl', ManagementProjectsCtrl);

function ManagementProjectsCtrl(serviceManagementDataTable, serviceManagementProjects, $mdDialog, $mdToast) {
    var vm = this;
    vm.DeletedDataTable = DeletedDataTable;
    vm.SaveDataTable = SaveDataTable;
    vm.SetEditDataTable = SetEditDataTable;
    vm.EditDataTable = EditDataTable;
    vm.Active = Active;
    vm.project = {};
    vm.dataProjects = [];
    vm.dtData = [];
    vm.dtColumns = [
        serviceManagementDataTable.AddColumns('id', 'ID').WithWidth(50).SortingBy('asc'),
        serviceManagementDataTable.AddColumns('name', 'Nazwa'),
        serviceManagementDataTable.AddColumns('action', 'Czynność'),
        serviceManagementDataTable.AddColumns('createdDate', 'Data utworzenia'),
        serviceManagementDataTable.AddColumns('grantedTime', 'Liczba przyznanych godzin'),
        serviceManagementDataTable.AddColumns('usedTime', 'Liczba wykorzystanych godzin')
    ];
    vm.config = {
        totalData: serviceManagementDataTable.SetNoDownloadData(),
        urlAdd: 'scripts/modules/managementProjects/views/addDataProject.html',
        urlEdit: 'scripts/modules/managementProjects/views/editDataProject.html'
    };

    Active();

    function Active() {
        vm.dtData.startDownload = true;
        console.log("Start DOWNLOAD " + Date());
        /*serviceManagementUsers.DownloadData.query().$promise.then(function(user) {
            vm.dataUsers = user;
            vm.dtData = serviceManagementDataTable.PrepareData(vm.dtColumns, user);
        });*/
        var get = [serviceManagementDataTable.GetCurrentPage().start, serviceManagementDataTable.GetPageSize()];
        serviceManagementProjects.DownloadData.query({
            limit: get.join()
        }).$promise.then(function(data) {
            vm.dataProjects = data;
            vm.dtData = serviceManagementDataTable.PrepareData(vm.dtColumns, data);
            console.log("End DOWNLOAD " + Date());
        });
    }

    function DeletedDataTable(currData, removeData) {
        var idDeleted = [];
        angular.forEach(removeData, function(val) {
            idDeleted.push(val.id);
        });

        serviceManagementProjects.DownloadData.remove({
            ids: idDeleted.join()
        }).$promise.then(function(project) {
            $mdToast.show(
                $mdToast.simple()
                .content('Usunięto ' + (idDeleted.length > 1 ? 'projektów' : 'projekt') + '.')
                .position("right top")
                .hideDelay(3000)
            );
        }, function(reason) {
            $mdToast.show(
                $mdToast.simple()
                .content('Wystąpił błąd podczas usuwania ' + (idDeleted.length > 1 ? 'projektów' : 'projektu') + '.')
                .position("left top")
                .hideDelay(3000)
            );
        });
    }

    function SaveDataTable(data) {
        serviceManagementProjects.DownloadData.save(data).$promise.then(function(project) {
            data.id = project.id;
            vm.dataProjects.push(data);
            vm.dtData = serviceManagementDataTable.PrepareData(vm.dtColumns, vm.dataProjects);
            $mdToast.show(
                $mdToast.simple()
                .content('Dodano projekt.')
                .position("right top")
                .hideDelay(3000)
            );
        }, function(reason) {
            $mdToast.show(
                $mdToast.simple()
                .content('Wystąpił błąd podczas dodawania projektu.')
                .position("left top")
                .hideDelay(3000)
            );
        });
    }

    function SetEditDataTable(event) {
        vm.project = vm.dataProjects[event.ids];
        return vm.project;
    }

    function EditDataTable(key, ret) {
        vm.dataProjects[key] = ret;
        vm.dtData = serviceManagementDataTable.PrepareData(vm.dtColumns, vm.dataProjects);

        serviceManagementProjects.DownloadData.update(serviceManagementDataTable.PrepareAjaxData(vm.dtData)).$promise.then(function(project) {
            $mdToast.show(
                $mdToast.simple()
                .content('Edytowano informacje o projekcie.')
                .position("right top")
                .hideDelay(3000)
            );
        }, function(reason) {
            $mdToast.show(
                $mdToast.simple()
                .content('Wystąpił błąd podczas edytowania informacji o projekcie.')
                .position("left top")
                .hideDelay(3000)
            );
        });
    }
}
})();

serviceManagementProjects.js

(function() {
'use strict';

angular
    .module('appManagementProjects')
    .factory('serviceManagementProjects', ServiceManagementProjects);

function ServiceManagementProjects($resource) {
    var data = [];
    var DownloadData = $resource('http://**********/api/projects', null, {
        'update': {
            method: 'PUT'
        }
    });
    var self = {
        firstDownload: false
    };
    var service = {
        DownloadData: DownloadData,
        SetNoFirstDownload: SetNoFirstDownload,
        IsFirstDownload: IsFirstDownload,
        DeletedProjects: DeletedProjects
    };
    return service;

    function DeletedProjects(selected) {
        angular.forEach(data, function(val, key) {
            if (selected.indexOf(val.ids) !== -1) {
                data.splice(key, 1);
            }
        });
    }

    function SetNoFirstDownload() {
        self.firstDownload = true;
    }

    function IsFirstDownload() {
        return !self.firstDownload;
    }
}
})();

addDataProject.html

<md-dialog class="md-default-theme addProjectForm">
<md-dialog-content>
    <h2 class="md-title">Dodawanie projektu</h2>
    <form name="addProject" onclick="return false;">
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.name" type="text" name="name" placeholder="Nazwa projektu" ng-required="true">
            <div ng-messages="addProject.name.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.action" type="text" name="action" placeholder="Czynność" ng-required="false">
            <div ng-messages="addProject.action.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.createddate" type="date" name="createdate" placeholder="Data utworzenia" ng-required="true">
            <div ng-messages="addProject.createddate.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.grantedtime" type="text" name="grantedtime" placeholder="Liczba przyznanych godzin" ng-required="true">
            <div ng-messages="addProject.grantedtime.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.usedtime" type="text" name="usedtime" placeholder="Liczba wykorzystanych godzin" ng-required="false">
            <div ng-messages="addProject.usedtime.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
    </form>
</md-dialog-content>
<div class="md-actions">
    <md-button type="button" ng-click="ctrl.vm.CancelDialog()">Anuluj</md-button>
    <md-button class="md-primary" aria-label="{{ctrl.vm.dialogConfig.confirm}}" type="submit" ng-click="ctrl.vm.HideDialog()" ng-disabled="editProject.$invalid" ng-bind="ctrl.vm.dialogConfig.confirm"></md-button>
</div>

editDataProject.html

<md-dialog class="md-default-theme addProjectForm">
<md-dialog-content>
    <h2 class="md-title">Edytowanie projektu</h2>
    <form name="editProject" onclick="return false;">
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.name" type="text" name="name" placeholder="Nazwa projektu" ng-required="true">
            <div ng-messages="addProject.name.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.action" type="text" name="action" placeholder="Czynność" ng-required="false">
            <div ng-messages="addProject.action.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.createdDate" type="date" name="createddate" placeholder="Data utworzenia" ng-required="true">
            <div ng-messages="addProject.createdDate.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container>
            <input ng-model="ctrl.vm.dialogData.grantedTime" type="text" name="grantedtime" placeholder="Liczba przyznanych godzin" ng-required="true">
            <div ng-messages="addProject.grantedTime.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
        <md-input-container flex>
            <input ng-model="ctrl.vm.dialogData.usedTime" type="text" name="usedtime" placeholder="Liczba wykorzystanych godzin" ng-required="false">
            <div ng-messages="addProject.usedTime.$error">
                <div ng-message="required">To pole jest obowiązkowe.</div>
            </div>
        </md-input-container>
    </form>
</md-dialog-content>
<div class="md-actions">
    <md-button type="button" ng-click="ctrl.vm.CancelDialog()">Anuluj</md-button>
    <md-button class="md-primary" aria-label="{{ctrl.vm.dialogConfig.confirm}}" type="submit" ng-click="ctrl.vm.HideDialog()" ng-disabled="editProject.$invalid" ng-bind="ctrl.vm.dialogConfig.confirm"></md-button>
</div>

managementProjects.html

<div management-data-table datatable="managementProjects.dtData" columnstable="managementProjects.dtColumns" config="managementProjects.config"></div>

datatable directibe

(function() {
'use strict';

angular
    .module('appManagementDataTable')
    .directive('managementDataTable', ManagementDataTable);

function ManagementDataTable($mdDialog) {
    return {
        restrice: 'A',
        scope: {
            datatable: '=',
            columnstable: '=',
            config: '=',
            managementDataTable: '@'
        },
        templateUrl: 'scripts/modules/datatable/views/dataTable.html',
        controller: 'ManagementDataTableCtrl',
        controllerAs: 'managementDT',
        link: function($scope, $element, $attr, $controller) {
            var controller = $element.parent().controller();

            $scope.selected = [];
            $scope.showProgress = true;
            $scope.toggleAllOn = false;

            function toggleAllOff() {
                $scope.toggleAllOn = false;
                $scope.selected = [];
                $controller.SetSelected(0, $scope.selected);
            }

            $scope.totalLength = $scope.datatable.totalLength;

            $scope.GetData = function() {
                if ($scope.config.totalData === true)
                    return false;
                else 
                    return true;
            }

            $scope.DeletedData = function() {
                var old = $scope.datatable;
                var returnData = [];
                var removeData = [];
                $scope.datatable = [];
                angular.forEach(old, function(val, key) {
                    if ($scope.selected.indexOf(val.ids) == -1) {
                        $scope.datatable.push(val);
                        delete val.ids;
                        delete val.values;
                        returnData.push(val);
                    } else {
                        delete val.ids;
                        delete val.values;
                        removeData.push(val);
                    }
                });

                toggleAllOff();

                if (controller.DeletedDataTable !== undefined) {
                    controller.DeletedDataTable(returnData, $controller.PrepareAjaxData(removeData));
                } else console.log("Error: DeletedDataTable is undefined");
            }

            $scope.AddData = function(ev) {
                $scope.dialogConfig = {
                    typ: 'add',
                    confirm: 'Dodaj'
                };
                if ($scope.config.urlAdd === undefined) {
                    console.log("Error: urlAdd in config is undefined");
                } else {
                    $scope.dialogData = {};
                    $mdDialog.show({
                            templateUrl: $scope.config.urlAdd,
                            parent: angular.element(document.body),
                            targetEvent: ev,
                            controller: function() {
                                this.vm = $scope;
                            },
                            controllerAs: 'ctrl'
                        })
                        .then(function(ret) {
                            if (controller.SaveDataTable !== undefined) {
                                controller.SaveDataTable(ret);
                            } else console.log("Error: SaveDataTable is undefined");
                        }, function() {});
                }
            }

            $scope.EditData = function(key, ev) {
                $scope.dialogConfig = {
                    typ: 'edit',
                    confirm: 'Edytuj'
                };
                if ($scope.config.urlEdit === undefined) {
                    console.log("Error: urlEdit in config is undefined");
                } else if (controller.SetEditDataTable !== undefined) {
                    var dat = controller.SetEditDataTable($scope.datatable[key]);
                    $scope.dialogData = dat;
                    $mdDialog.show({
                            templateUrl: $scope.config.urlEdit,
                            parent: angular.element(document.body),
                            targetEvent: ev,
                            controller: function() {
                                this.vm = $scope;
                            },
                            controllerAs: 'ctrl'
                        })
                        .then(function(ret) {
                            if (controller.EditDataTable !== undefined) {
                                controller.EditDataTable(key, ret);
                            } else console.log("Error: EditDataTable is undefined");
                        }, function() {});
                } else console.log("Error: SetEditDataTable is undefined");
            }

            $scope.HideDialog = function() {
                $mdDialog.hide($scope.dialogData);
            }

            $scope.CancelDialog = function() {
                $mdDialog.cancel();
            }

            $scope.GetColumnCount = function() {
                return $scope.columnstable.length + 2;
            }

            $scope.SetPageSize = function(val) {
                $controller.SetPageSize(val);

            }

            $scope.ToggleRow = function(keyRow) {
                if ($scope.selected.indexOf(keyRow) === -1)
                    $scope.selected.push(keyRow);
                else
                    $scope.selected.splice($scope.selected.indexOf(keyRow), 1);

                $controller.SetSelected(0, $scope.selected);

                angular.forEach($scope.datatable, function(val, key) {
                    if (val.ids == keyRow) {
                        $scope.datatable[key].checked = !$scope.datatable[key].checked;
                    }
                });
            }

            $scope.ToggleAll = function(data) {
                $scope.toggleAllOn = !$scope.toggleAllOn;
                var ids = [];
                $scope.selected = [];
                angular.forEach(data, function(val, key) {
                    ids.push(val.ids);
                    if ($scope.toggleAllOn)
                        $scope.selected.push(val.ids);
                });

                $controller.SetSelected(0, $scope.selected);

                angular.forEach($scope.datatable, function(val, key) {
                    if (ids.indexOf(val.ids) !== -1)
                        $scope.datatable[key].checked = $scope.toggleAllOn;
                });
            }

            $scope.SortingBy = function(key, sortable) {
                $controller.SetSorting(key, sortable);
            }

            $scope.GetSorting = function(key, sortable) {
                return $controller.IsSorting(key, sortable);
            }

            $scope.GetPageSize = function() {
                return $controller.GetPageSize();
            }

            $scope.GetCurrentPage = function() {
                return $controller.GetCurrentPage().currPage;
            }

            $scope.GetCurrentPageInformation = function() {
                var pages = $controller.GetCurrentPage();
                pages.end = pages.start + $controller.GetPageSize();
                pages.start += 1;

                return pages;
            }

            $scope.GetLastPage = function() {
                var totalLength = $scope.totalLength;
                var pageSize = $controller.GetPageSize();

                return Math.ceil(totalLength / pageSize);
            }

            $scope.SetCurrentPage = function(val) {
                $controller.SetCurrentPage(val);
                toggleAllOff();
                /*angular.forEach($scope.datatable, function(val, key) {
                    $scope.datatable[key].checked = false;
                });*/
                /** ADD */
                if (controller.Active !== undefined) {
                    controller.Active();
                } else console.log("Error: Active is undefined");
                /** END ADD */
            }

            $scope.Pages = function(totalLength) {
                //$scope.totalLength = totalLength;
                /** ADD */
                $scope.totalLength = $scope.datatable.totalLength;
                /** END ADD */
                var pageSize = $controller.GetPageSize();
                var totalPages = Math.ceil($scope.totalLength / pageSize);
                var currPage = $controller.GetCurrentPage().currPage;
                currPage = currPage > totalPages ? totalPages : currPage;
                $controller.SetCurrentPage(currPage);

                var pages = [];
                if (totalPages < 8) {
                    for (var i = 1; i <= totalPages; i++) {
                        pages.push(i);
                    }
                } else {
                    if (totalPages < 6) {
                        for (var i = 1; i <= totalPages; i++) {
                            pages.push(i);
                        }
                    } else if (currPage <= 5) {
                        for (var i = 1; i <= 7; i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(totalPages);
                    } else if (currPage > 5 && currPage + 3 < totalPages) {
                        pages.push(1);
                        pages.push('...');
                        for (var i = (currPage - 2); i <= (currPage + 2); i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(totalPages);
                    } else {
                        pages.push(1);
                        pages.push('...');
                        var j = totalPages - currPage;
                        var k = 6 - j;

                        for (var i = (currPage - k); i <= totalPages; i++) {
                            pages.push(i);
                        }
                    }
                }
                return pages;
            }
        }
    }
}
})();

1 个答案:

答案 0 :(得分:0)

您是否查看了organization提供的日期文档。

此外,您可以更改视图中的日期格式,日期属性,使用日期过滤器和格式“YYYY-MM-DD&#39;”进行过滤。请参阅here或者您可以在代码时更改日期格式,例如createdDate = $filter('date')(new Date(), 'yyyy-MM-dd')代码createdDate

希望这有帮助!