简体   繁体   中英

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 getting a problem where I end up with just an anchor, but the ng-click attribute will not appear.

Here is the code that I have in my directives template:

<div class="caption-box">
    <span ng-show="post.data.caption.text" ng-bind-html="post.data.caption.text"></span>
</div>

And in my link function:

for(var i = 0; i < scope.post.data.tags.length; i++){
    var str = scope.post.data.tags[i];
    var html = "<a ng-click='modalHashtag()'>" + scope.post.data.tags[i] + "</a>"
    scope.post.data.caption.text = scope.post.data.caption.text.replace(str, $sce.trustAsHtml(html));
}

The output I'm expecting is this, where function() is a function within a controller

<a ng-click="function()">#tag</a>

However all i'm getting is this

<a>#tag</a>

I've also tried using filters to replace the tags with HTML, and whilst it replaced the HTML correctly, the functions attached to each tag never worked upon click.

EDIT: Plunkr http://plnkr.co/edit/FWyZKn1fvdhvZD58HXug?p=preview

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:

http://jsfiddle.net/hv7Pj/9/

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('<div></div>').html(value).contents();
            var compiled = $compile(content);
            element.html('');
            element.append(content);
            scope.onClick = function (tag) {
                alert(tag);
            };

            compiled(scope)
        });
    }
};
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM