Last active
January 15, 2018 02:15
-
-
Save Lwdthe1/6f776dac48dc8f6dd30639d9f6be6add to your computer and use it in GitHub Desktop.
Angular directive for parsing links and username mentions in text and converting to html elements
This file contains hidden or 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
// example html: <p parse-entities data-parse-entities-url="_blank" data-parse-entities-mentions="true" ng-model="message.text"></p> | |
angularApp | |
.directive('parseEntities', function () { | |
var mentionPattern = /\B@[a-z0-9_-]+/gi; | |
var urlPattern = /[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi; | |
const VALID_ANCHOR_TARGETS = {'_self': '_self', '_blank': '_blank'} | |
VALID_ANCHOR_TARGETS['self'] = VALID_ANCHOR_TARGETS['_self'] | |
VALID_ANCHOR_TARGETS['blank'] = VALID_ANCHOR_TARGETS['_blank'] | |
return { | |
restrict: 'A', | |
require: 'ngModel', | |
replace: true, | |
scope: { | |
props: '=parseEntities', | |
ngModel: '=ngModel' | |
}, | |
link: function compile(scope, element, attrs, controller) { | |
scope.$watch('ngModel', function (value) { | |
var newHtml = value | |
// parse links | |
if (attrs.parseEntitiesUrl) { | |
var target = VALID_ANCHOR_TARGETS[attrs.parseEntitiesUrl] || '_blank' | |
newHtml = newHtml.replace('https://', '').replace('http://', '') | |
if(ImageUtils.isImageUrl(value)) { // the whole value would be a image string | |
newHtml = newHtml.replace(urlPattern, '<a class="js-parsedUrlAnchor" style="max-width:100%" target="'+target+'" href="//$&"><img style="max-width: 100%; height: auto" src="//$&"></a>'); | |
} else { | |
newHtml = newHtml.replace(urlPattern, '<a class="js-parsedUrlAnchor" target="'+target+'" href="//$&">$&</a>'); | |
} | |
} | |
// parse mentions | |
if (attrs.parseEntitiesMentions) { | |
newHtml = newHtml.replace(mentionPattern, '<strong class="js-parsedUsernameMention" title="$&">$&</strong>'); | |
} | |
// replace the html | |
element.html(newHtml); | |
}); | |
} | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment