Created
November 12, 2015 13:47
-
-
Save NenadP/70725e1a8b9d4f010ba8 to your computer and use it in GitHub Desktop.
Json to HTML angular filter simple demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
]); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"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