Angularjs指令替换文本

Nim*_*Net 19 javascript angularjs

我如何在angularjs中创建一个指令,例如获取此元素:

<div>Example text http://example.com</div>
Run Code Online (Sandbox Code Playgroud)

并将其转换为此

<div>Example text <a href="http://example.com">http://example.com</a></div>
Run Code Online (Sandbox Code Playgroud)

我已经将函数编写为自动链接函数中的文本并返回html(让我们调用函数"autoLink"),但我不会在我的指令上划伤.

我还想在元素中添加一个属性,将对象传递给指令.例如

<div linkprops="link.props" >Example text http://example.com</div>
Run Code Online (Sandbox Code Playgroud)

其中link.props是像{a:'bla bla',b:'waa waa'}这样的对象,它将作为第二个参数传递给autoLink函数(第一个是文本).

bml*_*ite 38

两种方式:

指示

app.directive('parseUrl', function () {
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;
    return {
        restrict: 'A',
        require: 'ngModel',
        replace: true,
        scope: {
            props: '=parseUrl',
            ngModel: '=ngModel'
        },
        link: function compile(scope, element, attrs, controller) {
            scope.$watch('ngModel', function (value) {
                var html = value.replace(urlPattern, '<a target="' + scope.props.target + '" href="$&">$&</a>') + " | " + scope.props.otherProp;
                element.html(html);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<p parse-url="props" ng-model="text"></p>
Run Code Online (Sandbox Code Playgroud)

过滤

app.filter('parseUrlFilter', function () {
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;
    return function (text, target, otherProp) {
        return text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>') + " | " + otherProp;
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<p ng-bind-html-unsafe="text | parseUrlFilter:'_blank':'otherProperty'"></p>
Run Code Online (Sandbox Code Playgroud)

注意:'otherProperty'例如,如果您想要将更多属性传递到过滤器中.

的jsfiddle

更新:改进替换算法.


exc*_*lsr 5

要回答这个问题的前半部分,没有额外的属性要求,可以使用Angular的linky过滤器:https://docs.angularjs.org/api/ngSanitize/filter/linky


Nea*_*eal 5

如果有多个链接,最高投票的答案不起作用。Linky 已经为我们完成了 90% 的工作,唯一的问题是它清理了 html,从而删除了 html/换行符。我的解决方案是只编辑链接过滤器(以下是 Angular 1.2.19)而不是清理输入。

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('<a ');
      if (angular.isDefined(target)) {
        html.push('target="');
        html.push(target);
        html.push('" ');
      }
      html.push('href="');
      html.push(url);
      html.push('">');
      addText(text);
      html.push('</a>');
    }
  };
}]);
Run Code Online (Sandbox Code Playgroud)