【问题标题】:Directive under ng-if doesn't get recompiled when inserted in DOMng-if 下的指令在插入 DOM 时不会重新编译
【发布时间】:2017-07-14 03:09:12
【问题描述】:

这是一个演示标题中描述的问题的示例:https://plnkr.co/edit/Xn1qgYftc5YHMsrGj0sh?p=preview

指令代码:

.directive('translate', function($compile) {
  return {
    compile: function(element) {
      var html = element.html().split('<br plural="">');
      return function(scope, element, attrs) {
        function c(h) {
          element.html(h);
          $compile(element.contents())(scope);
        }
        if (attrs.translate != '') {
          scope.$watch(function() {
            return scope.$eval(attrs.translate)
          }, function(val, oldval) {
            if (val == oldval && html[2] !== undefined) return;
            var p = html[2];
            html[2] = gettext(html[0], html[1], attrs.add !== undefined ? val + attrs.add : attrs.subtract !== undefined ? val - attrs.subtract : val);
            if (p != html[2]) c(html[2]);
          });
        } else c(gettext(html[0]));
      }
    }
  }
})

所以问题是当我切换回指令以使用 ng-if 显示时 - 它可能不会通过重新编译(?)完全重置,因此会导致行为不端。
如何跟踪指令何时从 DOM 中插入和删除?如果有办法,那么我可以用一个指标来解决这个问题。但一定有更好的办法吧?

【问题讨论】:

  • 你能用 ng-show 吗?
  • @mikelt21:在某些情况下,我想优化并改用ng-if,比如有许多不同的选择,一次只能显示一个,所以这不是解决方案。它存在于ng-show 中是有目的的。

标签: javascript angularjs angularjs-directive angularjs-compile angularjs-ng-if


【解决方案1】:

这样解决了:

.directive('translate', function($compile) {
  return {
    compile: function(element, attrs) {
      if (attrs.translate == '') {
        element.html(gettext(element.html()));
        return;
      }
      attrs.html = element.html().split('<br plural="">');
      return {
        post: function (scope, element, attrs) {
          delete attrs.html[2];
          scope.$watch(function () {
            return scope.$eval(attrs.translate);
          }, function (val) {
            var p = attrs.html[2];
            attrs.html[2] = gettext(attrs.html[0], attrs.html[1], attrs.add !== undefined ? val + attrs.add : attrs.subtract !== undefined ? val - attrs.subtract : val);
            if (p == attrs.html[2]) return;
            element.html(attrs.html[2]);
            $compile(element.contents())(scope);
          });
        }
      }
    }
  }
})

Live example

我认为我已经对其进行了足够好的优化,但请随时更正代码。

【讨论】:

  • 如果您将compile: function... 更改为link: function...,也可以使用您的原始代码
  • @mikelt21:我不知道它会如何工作。在我的指令中再次查看compile,它返回prepost 链接函数并在此之前保存未处理的HTML 代码。 link 函数无法实现相同的功能。
  • 啊,好吧,我没有仔细看你的代码,也没有解释代码应该做什么。这就是我想要得到的:link。我还稍微更改了 html 结构以避免重复的 html 代码。
  • @mikelt21:感谢您的努力,您给了我一个进一步优化它的想法。我现在已经更新了代码。
  • @mikelt21:顺便说一句,一旦您在指令内容中移动带有ng-repeat 的div,您使用link 函数的方法将无法按预期工作。见this
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2015-08-24
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多