如何在内容更改时进行角度链接更新

时间:2016-02-24 23:25:15

标签: javascript angularjs angularjs-directive angularjs-filter

我正在使用angular-linkify,这太棒了,但我遇到了一个问题,如果我更新了linkify的内容,它就不会运行再次连接过滤器。

<label linkify>{{item.text}}</label>

然后

item.text = item.text + 'more text';

...文本确实在视图中更新,但它没有链接。

基于this question,我尝试在指令的scope.$watch(element.html, ...)函数中使用scope.$on('$stateChangeSuccess', ...)link,但前者产生错误而后者不是&# 39; t触发。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为您可以使用linkify服务,如您在此处的示例中所示:https://github.com/scottcorgan/angular-linkify

首先向您的控制器注入这两项服务: linkify和$ sce

然后,而不是这样做:

item.text = item.text + 'more text';

尝试这样做:

item.text = $sce.trustAsHtml(linkify.twitter(item.text + 'more text'));

答案 1 :(得分:0)

Shabam,钉了它。

我修改了指令如下:

return {
  restrict: 'A',
  scope: {
    bind: '=ngBind'
  },
  link: function (scope, element, attrs) {
    var type = attrs.linkify || 'normal';
    $timeout(function () { element.html(linkify[type](element.html())); });
    if (attrs.ngBind) {
      scope.$watch('bind', function (now, old) {
        if (now) {
          $timeout(function () { element.html(linkify[type](now)); });
        }
      });
    }
  }
};

然后是html:

<label ng-bind="item.text" linkify></label>