【问题标题】:How to make angular linkify update when content changes内容更改时如何进行角度链接更新
【发布时间】:2016-02-24 23:25:14
【问题描述】:

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

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

然后

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

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

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

有什么想法吗?

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-filter


    【解决方案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'));
    

    【讨论】:

    • 嗯,这可能有效...除了 item.text 的值在应用程序的许多其他地方(并存储在后端等)中使用,因此它需要是文本,不是html。我希望能够触发它来更新...
    • 您可以将“$sce.trustAsHtml(linkify.twitter(item.text + 'more text'))”的结果分配给另一个变量而不是item.text并解决问题
    【解决方案2】:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-21
      • 2013-03-06
      • 1970-01-01
      • 2015-10-08
      • 2020-05-10
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      相关资源
      最近更新 更多