Angularjs directive to replace text

前端 未结 6 663
陌清茗
陌清茗 2020-12-04 18:05

How would I create a directive in angularjs that for example takes this element:

Example text http://example.com

And

6条回答
  •  不思量自难忘°
    2020-12-04 19:08

    The top voted answer does not work if there are multiple links. Linky already does 90% of the work for us, the only problem is that it sanitizes the html thus removing html/newlines. My solution was to just edit the linky filter (below is Angular 1.2.19) to not sanitize the input.

    app.filter('linkyUnsanitized', ['$sanitize', function($sanitize) {
      var LINKY_URL_REGEXP =
            /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/,
          MAILTO_REGEXP = /^mailto:/;
    
      return function(text, target) {
        if (!text) return text;
        var match;
        var raw = text;
        var html = [];
        var url;
        var i;
        while ((match = raw.match(LINKY_URL_REGEXP))) {
          // We can not end in these as they are sometimes found at the end of the sentence
          url = match[0];
          // if we did not match ftp/http/mailto then assume mailto
          if (match[2] == match[3]) url = 'mailto:' + url;
          i = match.index;
          addText(raw.substr(0, i));
          addLink(url, match[0].replace(MAILTO_REGEXP, ''));
          raw = raw.substring(i + match[0].length);
        }
        addText(raw);
        return html.join('');
    
        function addText(text) {
          if (!text) {
            return;
          }
          html.push(text);
        }
    
        function addLink(url, text) {
          html.push('');
          addText(text);
          html.push('');
        }
      };
    }]);
    

提交回复
热议问题