Angularjs directive with ng-click

Angularjs directive with ng-click

本文关键字:ng-click with directive Angularjs      更新时间:2023-09-26

我是Angularjs的新手,正在尝试创建一个字典指令,用锚标记搜索和替换文本。搜索和替换部分工作正常,但我无法让ng点击工作

HTML

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

角度

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

更新
下面的评论行使它按预期工作。

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

});

您需要编译您的元素。

编辑在循环后添加compile语句,如下面的注释所述。

txt = $compile(txt)(scope);