2014-09-11 47 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對象存儲到數組中。