AngularJS指令与ngClick函数替换标签 [英] AngularJS directive to replace tags with an ngClick function
问题描述
我目前正在试图建立一个指令,将采取帖子来自某项服务,然后遍历一个标签阵列,替换与HTML发生的任何情况。
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.
我得到在那里我最终只是一个锚的问题,但NG-点击属性将不会出现。
I'm getting a problem where I end up with just an anchor, but the ng-click attribute will not appear.
下面是code,我有我的指令的模板:
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>
我也尝试使用过滤器,以取代HTML的标记,虽然它正确地更换了HTML,连接到每个标签的功能从来没有在点击的工作。
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.
编辑:Plunkr http://plnkr.co/edit/FWyZKn1fvdhvZD58HXug?p= preVIEW
Plunkr http://plnkr.co/edit/FWyZKn1fvdhvZD58HXug?p=preview
推荐答案
所以我花了(很)长的时间,试图找到解决这个问题,我终于设法解决它得益于<一个href=\"http://stackoverflow.com/questions/16397707/angularjs-directive-to-replace-text-with-ng-click-in-it\">this问题/答案这里。
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:
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)
});
}
};
});
这篇关于AngularJS指令与ngClick函数替换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!