首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在更改作用域的指令中重新绘制/重新创建模板?

如何在更改作用域的指令中重新绘制/重新创建模板?
EN

Stack Overflow用户
提问于 2013-05-04 07:11:52
回答 1查看 1K关注 0票数 0

我正在尝试创建一个Twitter共享按钮指令,该指令会根据父模型进行更改

代码语言:javascript
复制
app.directive('twitterShare', function() {
  return {
    restrict: 'A',
    template: "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>",
    scope: {
      text: '=twitterShare'
    },
    link: function($scope, $element, $attrs, $model) {
      return $scope.$watch('text', function(value) {
         //??
      });
    }
  };
});

和指令

代码语言:javascript
复制
<div twitter-share="scopeModel"></div>

$scope.text正确地显示了我的$scope.scopeModel,但是由于twitter用iframe替换了a元素,元素本身就丢失了。当它改变时,我如何重新创建/重画,但应用某种油门,因为重新创建iframe是昂贵的。

尝试将其更改为

代码语言:javascript
复制
app.directive('twitterShare', function($compile, $timeout) {
return {
  restrict: 'A',
  scope: {
    text: '=twitterShare'
  },
  link: function($scope, element) {
    var $element;

    $element = "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>";

    $scope.$watch('text', function(value) {
      if (value != null) {
        $timeout(function() {
          element.html($compile($element)($scope));
          typeof twttr !== "undefined" && twttr !== null ? twttr.widgets.load() : void 0;
        });
      }
    });
  }
};
});

但是第二次更改$watch模型时,{{text}}占位符并没有更新。另一件奇怪的事情是,每次scopeModel更改时,$$watchers对象都会一直递增。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-04 20:26:36

答案是使用$interpolate而不是$compile。$interpolate使其能够处理字符串,并且不会像$compile那样堆叠$$watchers,而且在内存和CPU使用方面也比$compile容易得多

代码语言:javascript
复制
app.directive('twitterShare', function($interpolate, $timeout) {
    return {
      restrict: 'A',
      scope: {
        text: '=twitterShare'
      },
      replace: true,
      template: "<div ng-bind-html-unsafe='element'></div>",
      link: function($scope, element) {
        var $element;

        $element = "<a href=\"https://twitter.com/share\" data-count=\"none\" class=\"twitter-share-button\" data-text=\"{{text}}\" data-lang=\"pt-BR\"></a>";

        $scope.$watch('text', function(value) {
          if (value != null) {
            $timeout(function() {
              $scope.element = $interpolate($element)($scope);
              typeof twttr !== "undefined" && twttr !== null ? twttr.widgets.load() : void 0;
            });
          }
        });
      }
    };
  });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16368829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档