javascript - Angular 过滤器出错,将长 json 字符串编辑为 html 中的新行

标签 javascript html json angularjs

我是编码新手,在我的 html 中(使用 Angular)我从数据库 (Firebase) 调用了以下 json 数据:

<p>{{workout[0].box.info.training.strength.exercise[1].movement.freetext }}</p>

以下字符串在一长行的 HTML 中返回:

YGIG. Part A. 4 rounds of:. 3 min AMRAP. 400m run. Max RKBS in remaining time.  3 min rest between rounds. Part B. 4 rounds of: 3 min AMRAP. 400m row. Max Wall Balls in remaining time. 3 min rest between rounds

每次出现“.”时,我都希望文本在新行开始并创建了一个过滤器,它会生成一条错误消息。

HTML 是:

<p class="specificmovt">{{workout[0].cfhackney.week417.metcon.freetext|myFilter}}</p> 

过滤函数为:

var app = angular.module('starter.filters',[]);

app.filter('myFilter',function(){
   return function(input){
   return input.replace(/\./g, '\n');
   };
});

错误信息是:

TypeError: Cannot read property 'replace' of undefined
    at http://localhost:8100/js/filters.js:5:17
    at fn (eval at <anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21972:15), <anonymous>:4:500)
    at regularInterceptedExpression (http://localhost:8100/lib/ionic/js/ionic.bundle.js:23054:21)
    at Object.expressionInputWatch [as get] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:22956:26)
    at Scope.$digest (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24502:40)
    at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24778:24)
    at done (http://localhost:8100/lib/ionic/js/ionic.bundle.js:19191:47)
    at completeRequest (http://localhost:8100/lib/ionic/js/ionic.bundle.js:19363:7)
    at XMLHttpRequest.requestLoaded (http://localhost:8100/lib/ionic/js/ionic.bundle.js:19304:9)

正如其他 StackOverflow 帖子所建议的那样,我尝试添加\n 和“br”标签来代替“.”。进入 JSON 文件以创建一个新行 - 但这不起作用。

非常感谢您帮助找出将我的长 JSON 字符串换行或修复过滤器功能的最有效方法。

谢谢。

最佳答案

关于您的过滤器,您应该在过滤器函数的开头检查 input 是否未定义,如果是则返回(因为 undefined 没有替换函数)。

它被调用为 undefined 因为 Angulars 第一个 $digest 循环在你的数据可用之前运行。

这应该有效:

app.filter('myFilter',function(){
   return function(input){
       if(input == undefined){
           return;
       }
       return input.replace(/\./g, '\n');
   };
});    

如果您想使用 '\n' 作为换行符,您需要确保在周围元素上设置了 white-space: pre。这将使您的浏览器呈现换行符。

我希望我能帮上忙:)

关于javascript - Angular 过滤器出错,将长 json 字符串编辑为 html 中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421190/

相关文章:

html - IFrame 问题 : Footer is on top of iframe

json - Inno 安装程序 : How can I edit and retrieve value from a children section of a JSON file

java - 如何将 Jackson PrettyPrinter 格式 json 配置为 Gson

javascript - 更新 DecalGeometry 顶点、UV、

javascript - Vanilla JS - ES6 : . map() 不是函数

html - 在将图像发送到服务器之前上传并裁剪图像

php - 如何从动态创建的php表中收集数据

json - Spring MVC 中 Json 响应的后处理

javascript - 使用 jquery 在 div 周围创建边框

javascript - 如何使用 ref 回调将对象数组从一个组件传递到 React js 中的另一个组件