angularjs 应用程序中的通用日期格式,用于html文件标签

xmakbtuz  于 8个月前  发布在  Angular
关注(0)|答案(2)|浏览(57)

我正在Angular中更新一个应用程序,这不是我的日常工作。
我想将日期的格式设置为应用程序的常规值。换句话说,我想把格式作为一个字符串,作为一个常量存储在某个地方,或者作为一个全局字符串/设置。
到目前为止,我有:
<p>{{creationDate | date: 'd/M/y, hh:mm'}}</p>
我真正需要的是将'd/M/y, hh:mm'作为存储值,然后我可以在任何html文件中使用它。就这一点而言,从ts文件中的全局位置获取它对我来说很好。
首先,如何将格式设置为变量或常量?
下一步怎么做?

nwlqm0z1

nwlqm0z11#

假设你正在使用AngularJS,你可以将日期格式放在作用域中的变量中,或者使用模块.constant()并注入它:

angular.module("exampleApp", [])
  .constant("dateFmt", "d/M/y, hh:mm")
  .controller("dateFmtCtrl", function($scope, dateFmt) {
    $scope.creationDate = new Date();
    $scope.dateFmt = dateFmt;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
<div ng-app="exampleApp" ng-controller="dateFmtCtrl">
  <p>{{creationDate | date: dateFmt}}</p>
</div>
w51jfk4q

w51jfk4q2#

创建共享服务:date-format.service.ts

import { Injectable } from '@angular/core';
        
        @Injectable({
          providedIn: 'root',
        })
        export class DateFormatService {
          dateFormat: string = 'd/M/y, hh:mm';
        }

在组件中注入服务:

import { Component } from '@angular/core';
    import { DateFormatService } from './date-format.service';
    
    @Component({
      selector: 'app-my-component',
      template: '<p>{{creationDate | date: dateFormat}}</p>',
    })
    export class MyComponent {
       creationDate: Date;
  dateFormat: string;

  constructor(private dateFormatService: DateFormatService) {
    this.creationDate = new Date();
    this.dateFormat = this.dateFormatService.dateFormat; // Access the dateFormat property from the service
   
  }
    }

相关问题