0

这是一个演示标题中描述的问题的示例: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 中插入和删除?如果有办法,那么我可以用一个指标来解决这个问题。但一定有更好的方法,对吧?

4

1 回答 1

0

像这样解决它:

.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);
          });
        }
      }
    }
  }
})

活生生的例子

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

于 2017-02-23T16:23:59.763 回答