Angularjs Directive To Replace Tags With An Ngclick Function
I'm currently trying to build a directive that would take posts from a certain service, and then iterate through a 'tags' array, replacing any instances that occur with HTML. I'm g
Solution 1:
So I've spent a (very) long time trying to find a solution to this problem and I finally managed to solve it thanks to this question/answer here.
This is the resulting directive that solved my problem with what I wanted if anyone else has trouble:
app.directive('parseTags', function ($compile) {
var pattern = /(^|\s)#([^\s]+)/g;return {
restrict: 'A',
require: 'ngModel',
replace: true,
scope: {
ngModel: '=ngModel'
},
link: functioncompile(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('<div></div>').html(value).contents();
var compiled = $compile(content);
element.html('');
element.append(content);
scope.onClick = function (tag) {
alert(tag);
};
compiled(scope)
});
}
};
});
Post a Comment for "Angularjs Directive To Replace Tags With An Ngclick Function"