#hashtag parse directive
HTML
<div ng-controller="Ctrl">
<message caption="text"></message>
</div>
CSS
p {
padding-top: 10px;
}
input {
width: 500px;
}
JavaScript
var app = angular.module('app', []);
app.directive('message', function () {
return {
restrict: 'E',
scope: {
caption: '='
},
template: '<div><p parse-tags ng-model="caption"></p></div>'
}
});
app.directive('parseTags', function ($compile) {
var pattern = /(^|\s)#([^\s]+)/g;
return {
restrict: 'A',
require: 'ngModel',
replace: true,
scope: {
ngModel: '=ngModel'
},
link: function compile(scope, element, attrs, controller) {
scope.$watch('ngModel', function (value) {
angular.forEach(value.match(pattern), function (tag) {
var nohash = tag.replace(/#/g, '');
console.log(nohash);
value = value.replace(tag, "<a ng-click='onClick(\"" + nohash + "\")'>" + tag + "</a>");
});
var content = angular.element('<span></span>').html(value).contents();
var compiled = $compile(content);
element.html('');
element.append(content);
scope.onClick = function (tag) {
alert(tag);
};
compiled(scope)
});
}
};
});
function Ctrl($scope) {
$scope.text = 'this is an example #of #parsing #hash #tags with normal #text in between';
}