var app = angular.module('plunker', ['hashtagify']);
app.controller('MainCtrl', ['$scope', '$sce',
function($scope, $sce) {
$scope.tag = {
text: 'Hey @Joe where you goin\' with that #gun in your hand?'
};
$scope.tagUserClick = function(e) {
var tagText = e.target.innerText;
alert('tagUserClick, tagText: ' + tagText);
};
$scope.tagTermClick = function(e) {
var tagText = e.target.innerText;
alert('tagTermClick, tagText: ' + tagText);
};
// You could define 'tagUserClick' and 'tagTermClick'
// on the '$rootScope'. This way you can handle whatever
// logic you want for hashtags in one place rather than
// having to define it in each controller.
$scope.trustHtml = function(html) {
// Sanitize manually if necessary. It's likely this
// html has already been sanitized server side
// before it went into your database.
// Don't hold me liable for XSS... never assume :~)
return $sce.trustAsHtml(html);
};
}
]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS hashtagify</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.16"></script>
<script src="angular-hashtagify.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>angular hashtagify directive example:</p>
<p ng-bind-html="trustHtml(tag.text)"
hashtagify
term-click="tagTermClick($event)"
user-click="tagUserClick($event)">
</p>
<!-- or you can do this
<p hashtagify
term-click="tagTermClick($event)"
user-click="tagUserClick($event)">
{{tag.text}}
</p>
-->
</body>
</html>
/* Put your css in here */
a.hashtag {
color: #07c;
cursor: pointer;
}
a.hashtag:hover {
text-decoration: underline;
}
angular.module('hashtagify', []);
angular.module('hashtagify')
.directive('hashtagify', ['$timeout', '$compile',
function($timeout, $compile) {
return {
restrict: 'A',
scope: {
uClick: '&userClick',
tClick: '&termClick'
},
link: function(scope, element, attrs) {
$timeout(function() {
var html = element.html();
if (html === '') {
return false;
}
if (attrs.userClick) {
html = html.replace(/(|\s)*@(\w+)/g, '$1<a ng-click="uClick({$event: $event})" class="hashtag">@$2</a>');
}
if (attrs.termClick) {
html = html.replace(/(^|\s)*#(\w+)/g, '$1<a ng-click="tClick({$event: $event})" class="hashtag">#$2</a>');
}
element.html(html);
$compile(element.contents())(scope);
}, 0);
}
};
}
]);