我是Angularjs的新手,正在尝试创建一个字典指令,用于搜索和替换带锚标记的文本。搜索和替换部分工作正常,但我不能让ng-click工作。
的 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);
}
};
});