2017-05-25 110 views
0

我有一个角指令,搜索用户提交的文本,然后用锚标记替换的URL。角指令,该指令要求在控制器范围内的功能

function findUrls($compile) { 
    var linkPatterns = new Array({ 
    pattern: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, 
    template: '&nbsp;<a class="absolute_link" href="$1" target="_blank">$1</a>' 
    }, 
    { 
    pattern: /(^|[^\/])(www\.[\S]+(\b|$))/ig, 
    template: '&nbsp;<a class="absolute_link" href="http://$2" ng-click="alert(\'hello\')" target="_blank">$2</a>' 
    }, 
    { 
    pattern: /([a-z0-9._-][email protected][a-z0-9._-]+\.[a-zA-Z0-9._-]+)/ig, 
    template: '&nbsp;<a class="absolute_link" href="mailto:$1" ng-click="alert(\'hello\')" target="_blank">$1</a>' 
    }, 
    { 
    pattern: /(^|[^[email protected]\\\/._-])([a-z0-9]{0,256}\.(com|net|org|edu)([a-z0-9\/?=\-_#]{0,256})?(\b|$))/ig, 
    template: '&nbsp;<a class="absolute_link" href="http://$2" ng-click="alert(\'hello\')" target="_blank">$2</a>' 
    }); 

    return { 
    restrict: 'AC', 
    link: function (scope, elem, attrs) { 
     if (attrs.ngBind) { 
     scope.$watch(attrs.ngBind, _.debounce(wrapUrls)); 
     } 
     if (attrs.ngBindHtml) { 
     scope.$watch(attrs.ngBindHtml, _.debounce(wrapUrls)); 
     } 

     function wrapUrls(text) { 
     var html = elem.html(); 
     var newHtml = html; 

     linkPatterns.forEach((item) => { 
      newHtml = newHtml.replace(item.pattern, item.template); 
     }); 

     if (html !== newHtml) { 
      elem.html(newHtml); 
      $compile(elem.contents())(scope); 
     } 
     } 
    } 
    }; 
} 

当用户点击我希望能够捕捉到点击记录它所属于的对象的一些信息的环节之一。但是,指令不知道这些属于哪个对象,因此应该在控制器上处理记录点击的代码。

我想要的指令,通知这些元素之一被点击,控制器将记录对象的属性的控制器,但我不知道从哪里开始。

回答

1

你可以通过控制器的功能的指令和链接被点击

return { 
    restrict: 'AC', 
    scope: {    // **** Add this ***** 
     alert: '&' 
    } 
    link: function (scope, elem, attrs) { 
    if (attrs.ngBind) { 
     scope.$watch(attrs.ngBind, _.debounce(wrapUrls)); 
    } 
    if (attrs.ngBindHtml) { 
     scope.$watch(attrs.ngBindHtml, _.debounce(wrapUrls)); 
    } 

    function wrapUrls(text) { 
     var html = elem.html(); 
     var newHtml = html; 

     linkPatterns.forEach((item) => { 
      newHtml = newHtml.replace(item.pattern, item.template); 
     }); 

     if (html !== newHtml) { 
      elem.html(newHtml); 
      $compile(elem.contents())(scope); 
     } 
    } 
} 

<div DIRECTIVE_NAME alert="notify(msg)"></div> //controllers notify function

当从指令调用它