Skip to content

Instantly share code, notes, and snippets.

@NenadP
Created November 12, 2015 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NenadP/70725e1a8b9d4f010ba8 to your computer and use it in GitHub Desktop.
Save NenadP/70725e1a8b9d4f010ba8 to your computer and use it in GitHub Desktop.
Json to HTML angular filter simple demo
angular.module("myApp").filter("jsonToHtml", [
function () {
return function (json) {
var html = "",
/**
* @param element {Object} - content inside an element
* @returns {String}
* @private
*/
_createElement = function (element) {
return "<" + element.tag + ">" + element.content + "</" + element.tag + ">"
},
/**
*
* @param elements {Array} - Array of li element specification
* @returns {string}
* @private
*/
_createList = function (elements) {
var list = {
tag: "ul",
content: ""
};
angular.forEach(elements.content, function (element) {
list.content += _createElement(element);
});
return list;
};
/**
* Iterates through each element and executes appropriate markup builder
*/
angular.forEach(json, function (element, index) {
/**
* Specification of elements and procedure how to create them
* @type {{p: Function, ul: Function}}
*/
var build = {
p: function() {
return _createElement(element);
},
ul: function () {
var list = _createList(element);
return _createElement(list);
}
};
html += build[element.tag]();
});
return html;
}
}
]);
[
{
"tag": "p",
"content": "My paragraph content"
},
{
"tag": "ul",
"content": [
{
"tag": "li",
"content": "Content of 1st element"
},
{
"tag": "li",
"content": "Content of 2nd element"
},
{
"tag": "li",
"content": "Content of 3rd element"
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment