javascript - AngularJS 指令用 ngClick 函数替换标签

标签 javascript angularjs

我目前正在尝试构建一个指令,该指令将从某个服务获取帖子,然后遍历“标签”数组,用 HTML 替换出现的任何实例。

我遇到了一个问题,我最终只有一个 anchor ,但不会出现 ng-click 属性。

这是我的指令模板中的代码:

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

在我的链接函数中:

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));
}

我期待的输出是这样的,其中 function() 是 Controller 中的一个函数

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

但是我得到的只是这个

<a>#tag</a>

我也尝试过使用过滤器用 HTML 替换标签,虽然它正确地替换了 HTML,但每个标签所附的功能在点击时从未起作用。

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

最佳答案

所以我花了(很)长的时间试图找到解决这个问题的方法,感谢this question/answer here,我终于设法解决了它。 .

如果其他人遇到问题,这是解决我想要的问题的结果指令:

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)
        });
    }
};
});

关于javascript - AngularJS 指令用 ngClick 函数替换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22640527/

相关文章:

javascript - IE 9 getAttribute 方法工作

javascript - KNockout JS - 加载外部模板

javascript - 具有一些特殊要求的 Angular 图表

javascript - 我想移动多个数组列表中的元素

javascript - 我想更改 <code> 标签内元素的颜色不起作用

javascript - 将图像保存到本地存储 - Canvas

javascript - 如何在 AngularJS 中添加动态 div?

javascript - 用 Angular 连接两个 json 数组时“对象不是函数”

html表单在特定输入上按回车键时阻止提交

javascript - 查找元素与左侧的距离