简体   繁体   English

Angular 字符串格式时的js插值问题

[英]Angular js interpolation issue when string format

I am trying to format the string in the HTML.我正在尝试格式化 HTML 中的字符串。 This is my html Sample这是我的 html 样品

      <tr ng-repeat="dob in userId.dobs">
                <td align="center">{{$index + 1}}</td>
                <td>{{dob.dateType}}</td>
                <td>{{dob.birthDate}}</td>
                <td>{{dob.dateYear}}</td>
                <td>{{dob.fromYear}}</td>
                <td>{{dob.toYear}}</td>
            </tr>

Currently my {{dob.fromYear}}show like 1973/01/21.目前我的 {{dob.fromYear}} 节目像 1973/01/21。 But I need to split this string and keep only the year.但我需要拆分这个字符串并只保留年份。 Its like below {{dob.fromYear}} show like 1973. I tried to do it using below technique就像下面的 {{dob.fromYear}} 显示像 1973 年一样。我尝试使用以下技术来做到这一点

 <td>{{dob.fromYear.split('/')}}</td>

now my result like ["1973","01","21"]现在我的结果像 ["1973","01","21"] 在此处输入图像描述

I need to display only the year.我只需要显示年份。 How i do it.?我是怎么做的。?

You should create a pipe.您应该创建一个 pipe。 Pass the dob string to the pipe and inside the pipe you can do some text manipulation to get only the year.将 dob 字符串传递给 pipe 和 pipe 内部,您可以进行一些文本操作以仅获取年份。

const year = "1111/22/33".split("/").slice(0,1).join()
return year;

This code first splits the string.此代码首先拆分字符串。 Then slice(0,1) picks the year part and .join() converts the [1111] into a string.然后slice(0,1)选择年份部分, .join()[1111]转换为字符串。

You can try你可以试试

dob.fromYear.split('/')[0]

But i think this could be problematic if the date is in another format.但我认为如果日期是另一种格式,这可能会出现问题。 So better to use:所以最好使用:

new Date(dob.fromYear).getFullYear()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM