简体   繁体   English

带有ng-click的Angularjs指令

[英]Angularjs directive with ng-click

I am new to Angularjs and are trying to create a dictionary directive that searches and replaces texts with anchor tags. 我是Angularjs的新手,正在尝试创建一个字典指令,该指令搜索和替换带有定位标记的文本。 The search and replace part works fine but i can't get the ng-click to work. 搜索和替换部分工作正常,但我无法使ng-click正常工作。

HTML HTML

<div mk-dct>Lorem ipsum [dolor] sit [amet]</div>

Angular

app.directive('mkDct', function () {
var pattern = /\[([^\]]+)\]/g;
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var txt = element.html();
        var m = txt.match(pattern);

        for(var i = 0; i < m.length; i++){
            var word = m[i].substring(1, m[i].length-1);
            txt = txt.replace(m[i], '<a class="dict-item" ng-click="func(\''+word+'\')" href="#">'+ word + '</a>');
        }

        element.html(txt);
    }
};

UPDATE UPDATE
The commented lines below made it work as expected. 下面的注释行使其按预期运行。

app.directive('mkDct', function ($compile) {
var pattern = /\[([^\]]+)\]/g;
return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attrs) {
        var txt = element.html();
        var m = txt.match(pattern);

        for(var i = 0; i < m.length; i++){
            var word = m[i].substring(1, m[i].length-1);
            txt = txt.replace(m[i], '<a class="dict-item" ng-click="func(\''+word+'\')" href="#">'+ word + '</a>');
        }

        // Compile to template.
        txt = $compile(txt)(scope);

        // Clear and append.
        element.empty().append(txt);
    }
};

}); });

You need to compile your element. 您需要编译您的元素。

EDIT Add compile statement after loop as discussed in comments below. 编辑循环后添加编译语句,如下面的注释所述。

txt = $compile(txt)(scope);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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