AngularJS和JSON多行字符串

AngularJS and JSON with multiline string

本文关键字:字符串 JSON AngularJS      更新时间:2023-09-26

我已经在JSON文件中组织了我的数据,其中包含多行字符串,在数组中分隔。这样的:

[
    {
        "name": "1. Some Name",
        "id": "1",
        "description": [
            "Some long text 1 ",
            "Some long text 2 "
       ]
    },
    {
        "name": "2. Some Name",
        "id": "2",
        "description": [
            "Some long text 1 ",
            "Some long text 2 "
        ]
    }
]

然后在我的视图中,我想在description中显示文本:

<ion-view view-title="">
<ion-content>
    <div class="card">
        <div class="item item-text-wrap" 
             ng-repeat="rule in rules | filter: { id: whichid }">
            {{ rule.description }}
        </div>
    </div>
</ion-content>

我的输出是这样的:

["Some long text 1","Some long text 2"]

如何删除(或过滤)字符'[',' "'和','?

或者如果我使用ng-bind-html="rule.description"指令,我得到:

Some long text 1 ,Some long text 2

基本上这是一个很好的输出,但是它们包含一个逗号','(它在数组中)。

您也可以尝试Array.join()方法。

链接:Array.join ()

在你的情况中:{{rule.description.join (' ') }}

试试

 <div class="item item-text-wrap" 
         ng-repeat="rule in rules | filter: { id: whichid }">
        <span ng-repeat="d in rule.description">{{ d }}</span>
    </div>

这也给了我很多悲伤。然而,我用一个定制的管道解决了它。做一个管道的研究,但这应该有帮助:

管道/arraytextfix/arraytextfix。ts(管道文件):

import { Pipe, PipeTransform } from '@angular/core';
/**
 * Generated class for the ArraytextfixPipe pipe.
 *
 * See https://angular.io/api/core/Pipe for more info on Angular Pipes.
 */
@Pipe({
  name: 'arraytextfix',
})
export class ArraytextfixPipe implements PipeTransform {
  /**
   * This is a very important pipe, as it removes a joining
   * comma, as outlined on this page: https://stackoverflow.com/questions/39557436/angularjs-and-json-with-multiline-string
   */

  transform(value) { 
    value = value.join(' ');     
    return value
  } 
}

另一件重要的事情是,将管道文件添加到需要使用它的文件的模块中。

例如:

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ProjectsPage } from './projects'; 
import { TranslateModule } from '@ngx-translate/core'; // For translations to work
import { ArraytextfixPipe } from "../../pipes/arraytextfix/arraytextfix" // ADD THIS
@NgModule({
  declarations: [
    ProjectsPage,
    ArraytextfixPipe // ADD THIS
  ],
  imports: [
    TranslateModule, // For translations to work
    IonicPageModule.forChild(ProjectsPage),
  ],
})
export class ProjectsPageModule {}

然后,(对我来说)你可以用类似的方式处理所有的数据,甚至还可以使用翻译管道:

  <p [innerHTML]="'PROJECTS.BODY' | translate | arraytextfix"></p>

这基本上是我的i18n/en。Json数据提要:

{
"PROJECTS": 
  {
    "HEADING": "Projects",
    "DESCRIPTION": "A default description",
    "BODY": ["bodytext line 1 <p>even has support for a paragraph</p>",
    "<p>Works well on line 2</p>",
    "line 3"]
  } 
}

希望对大家有所帮助