angularjs,$编译模板和NG-重复 [英] angularjs, $compiled templates and ng-repeat

查看:287
本文介绍了angularjs,$编译模板和NG-重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从本质上讲,我需要两个模板指令编译函数内。
我编译它们的指令编译阶段一劳永逸(通过$编译)。
在该指令的链接阶段,我观看范围可变,并应用一个或另一个编译模板范围

Essentially, I take two templates inside a compile function of a directive. I compile them once and for all (via $compile) in the compile phase of the directive. In the link phase of the directive, I watch a scope variable and applies one or the other compiled template to the scope.

testApp.directive('testField', ['$compile', function ($compile) {
  return {
    restrict: 'E',
    scope: true,
    compile: function(tElement, tAttrs) {
      var viewFn = $compile("<div>View: <span ng-repeat='x in [1,2,3]'>{{x}}</span></div>");
      var editFn = $compile("<div>Edit: <span ng-repeat='x in [4,5,6]'>{{x}}</span></div>");

      return function (scope, element, attrs) {
        var innerScope = null;

        scope.$watch("mode", function (mode) {
          if (innerScope) innerScope.$destroy();
          innerScope = scope.$new();

          if (mode == 'VIEW') {
              element.empty().append(viewFn(innerScope));
          } else {
              element.empty().append(editFn(innerScope));
          }
        });
      };
    }
  };
}]);

它工作正常,除了当模板包括伍重复,是不是在这种情况下,行为怪异的根元素:

It works fine, except when the template includes a Ng-repeat that is not the root element in which case it behave strangely:

要重现,去 http://plnkr.co/edit/RCqlNWTVdXVoMQCkFcQn? p = preVIEW
和开关一对夫妇的时间为编辑查看。

To reproduce, go to http://plnkr.co/edit/RCqlNWTVdXVoMQCkFcQn?p=preview And switch a couple of time from Edit to View.

您会发现随时间增长NG-重复迭代次数。
第一次,它显示123和456,像它应该

You'll notice the number of iterations of ng-repeat grows over time. First time, it displays 123 and 456, like it should

第一来回查看和编辑之间后,显示123123和456456

After the first back and forth between view and edit, it displays 123123 and 456456

和它让每一个加入你做的查看和编辑之间的来回时间一次迭代。

And it keeps adding one iteration every time you do a back and forth between view and edit.

推荐答案

也许你可以做喜欢的这个

首先,您在您的视图直接注入新的DOM。之后,抓住它并应用$编译。

Firstly, you inject new dom directly in your view. After, catch it and apply $compile.

这样的;

var viewFn = "<div>View: <span ng-repeat='x in [1,2,3]'>{{x}}</span></div>";
...
element.html(viewFn);
...
$compile(tElement.contents())(innerScope);

这篇关于angularjs,$编译模板和NG-重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆