If you have ever developed web applications including social activity, like messaging, you definitely had a moment, when you need to add emoticons to your message board. Here is an example of AngularJS directive to convert symbols to emotional icons.
Emoticons map:
angular.module("myApp").value('Emoticons', {
':-)': 'http://www.freesmileys.org/smileys/smiley-basic/biggrin.gif',
':)': 'http://www.freesmileys.org/smileys/smiley-basic/biggrin.gif',
':D': 'http://www.freesmileys.org/smileys/smiley-basic/laugh.gif',
':-D': 'http://www.freesmileys.org/smileys/smiley-basic/laugh.gif',
':-|': 'http://www.freesmileys.org/smileys/smiley-basic/mellow.gif',
':|': 'http://www.freesmileys.org/smileys/smiley-basic/mellow.gif',
':-p': 'http://www.freesmileys.org/smileys/smiley-basic/tongue.gif',
':p': 'http://www.freesmileys.org/smileys/smiley-basic/tongue.gif',
':-(': 'http://www.freesmileys.org/smileys/smiley-basic/sad.gif',
':(': 'http://www.freesmileys.org/smileys/smiley-basic/sad.gif'
});
Directive:
angular.module("myApp").directive("withEmoticons", function (Emoticons, $timeout) {
return {
link: function postLink(scope, element, attrs) {
scope.replaceEmoticons = function (text) {
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
// build a regex pattern for each defined property
for (var i in Emoticons) {
if (Emoticons.hasOwnProperty(i)) { // escape metacharacters
patterns.push('(' + i.replace(metachars, '\\$&') + ')');
}
}
// build the regular expression and replace
return text.replace(new RegExp(patterns.join('|'), 'g'), function (match) {
return Emoticons[match] ?
'
' :
match;
});
};
$timeout(function () {
element.html(scope.replaceEmoticons(element.html()));
});
scope.$watch(function () {
return element.html();
}, function onChange(newVal, oldVal) {
if (newVal !== oldVal) {
$timeout(function () {
element.html(scope.replaceEmoticons(element.html()));
});
}
});
}
};
});
In HTML:
{{message}}