AngularJS directive to replace text with ng-click in it

↘锁芯ラ 提交于 2019-12-04 21:53:20

Take a look at my fork of your fiddle: http://jsfiddle.net/joakimbeng/aVjtv/1/ To make it work you need to use the $compile provider. My example isn't that clean, but I hope you get the point :)

Add the $compile dependency and compile your changed html:

app.directive('parseUrl', function($compile) {
    ...
    link: function compile(scope, element, attrs, controller) {
        angular.forEach(value.match(urlPattern), function(url) {
            value = value.replace(url, "<a target=\"" + scope.props.target + "\" ng-click='onClick()'>" + url +"</a>");
        });
        // The wrapping of the content in a div is required because
        // Angular wants only one element at root level
        var content = angular.element('<div></div>').html(value).contents();
        var compiled = $compile(content);
        element.html(''); // Clearing old text
        element.append(content); // Using append because "content" is DOMElements now, instead of a string
        scope.onClick= function () {
            console.log('clicked');
        };
        compiled(scope); // Linking compiled elements to scope
     ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!