2014-09-11 49 views
0

我正在学习AngularJS并退出有关以JSON格式存储数据的信息。 我正在构建一个真正的应用程序来学习一个真正的项目。JSON存储HTML

这是一本在线杂志。现在我将所有文章基本数据存储在articles.json中。这样我可以将所有基本文章数据推送到主页。

[ 
    { 
     "id":"1", 
     "category": "Activity", 
     "title": "Title goes here", 
     "short_desc": "Short description goes here", 
     "images": [ 
      "img/article-img.jpg" 
     ] 
    }, 
    { 
     "id":"1", 
     "category": "Activity", 
     "title": "Title goes here", 
     "short_desc": "Short description goes here", 
     "images": [ 
      "img/article-img.jpg" 
     ] 
    }, ... 
] 

然后根据文章ID将用户引导到一个新的模板并加载与URL文章相关的JSON文件:article1.json。它看起来像这样。

{ 
    "id":"1", 
    "category": "Activity", 
    "title": "Title goes here", 
    "html_desc": "<h1>Article subtitle goes here<h1><p>Paragraph text<\p>", 
    "images": [ 
     "img/featured-img.jpg" 
    ] 
} 

当然,我碰到的问题,在JSON,我不能,很容易使用HTML标签或即使我能,这将是文章的段落和标题转换成JSON格式的噩梦。

请指导我采取最佳做法。我假设我正在尝试处理数据的方式中缺少一些关键部分。也许我应该使用一些数据库来存储数据,而不是JSON。

请指教使用基于JS的框架如AngularJS和数据存储的最佳实践。

+0

你能提供一个plnkr吗? – 2014-09-11 12:47:29

回答

3

您可以在AngularJS直接绑定的html:

<div ng-repeat="article in articles"> 
    <div ng-bind-html="article.html_desc"></div> 
</div> 
+0

是的,工作。我将ngSanitize添加到应用中,如下所述:https://docs.angularjs.org/api/ng/directive/ngBindHtml。另外请注意,凡是将使用JSON格式的HTML的人,为避免多行问题,请使用http://www.willpeavy.com/minifier/等HTML精简版服务将您的漂亮HTML转换为一行。 – 2014-09-11 17:11:35

1

这是如何HTML数据添加到JSON的例子。 JSON帮助您快速检索数据并且非常有效。

{ 
    "title":"mongoose connect", 
    "description":"<p> Aaron, thanks. I read the doc on connection pools and think I understand it. The problem I am having is defining the db connection in the app.js file and then using that connection in my model definition files (one model per file) and in the routing files. I've tried the global.conn idea that Daniel providedcouldn't get it to work and the separate index.js file that Sergey suggested but couldn't get it work either. Is there an example of an express appsp that uses createConnection to create one connection that is shared in separate modules? – </p>", 
    "tags":["node js","mongoose","database mongodb connect","mongoose connect"], 
    "code":"<code> var mongoose = require('mongoose');<br> &nbsp;mongoose.connect('mongodb://127.0.0.1:27017/mytest'); </code>", 
    "created_on":" -- 04/10/2015", 
    "author":" -- by aqib" 
} 

这样您就可以存储html数据并可以使用密钥访问它。您可以将许多JSON对象存储到数组中。