【问题标题】:Angularjs: Compile ng-repeat dynamicallyAngularjs:动态编译 ng-repeat
【发布时间】:2017-01-24 11:08:24
【问题描述】:

我发现 Angularjs 有一些奇怪的行为。我的指令只是将ng-repeat 添加并编译到我的dom 元素中。但是,范围变量 item 不可访问。请看下面的代码进行解释。

var demo = angular.module('demo', []);
demo.directive('customRepeat', function($compile) {
    return {
      priority: 2000,
      restrict: 'A',
      compile: function(element){
        element.attr('ng-repeat', 'item in [1,2,3,4,5,6]')
          
        return function(scope, element) {
          $compile(element)(scope)
        }
      }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app='demo'>
    <h3>My Items</h3>
    <div custom-repeat>
      Item: {{item}}
    </div>
</div>

谁有一些 Angularjs 技能来解决这个问题?

注意尝试使用旧版本的 Angularjs(比如 1.2.x)运行它,您会发现它按预期工作。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    在修改原始 DOM 时编译指令的正确方法是,从指令编译函数(如 var compileFn = $compile(element))创建 compileFn,然后在链接函数中使用喜欢的 scope 重新编译元素。这样,您还将在 Angular 1.2.X 和 1.6.X 版本中看到 Maximum call stack exceed error。通过打开控制台检查this plunker

    基本上发生的事情是,您在指令元素上添加一个ng-repeat 并再次重新编译该元素,这将导致再次编译customDirective,并且这个过程将无限地继续发生。所以在再次编译元素之前,你应该确保你已经删除了custom-report 指令属性。那将不允许custom-report无限执行。

    var demo = angular.module('demo', []);
    demo.directive('customRepeat', function($compile) {
        return {
          priority: 2000,
          restrict: 'A',
          compile: function(element){
            element.attr('ng-repeat', 'item in [1,2,3,4,5,6]')
            element.removeAttr('custom-repeat');
            //this line is need for compilation of element
            var compile = $compile(element);
            return function(scope, element) {
              compile(scope); //linking scope
            }
          }
        }
    });
    

    Plunker Demo

    【讨论】:

    • 也许我不清楚。如果您运行代码,您将看到{{item}} 没有被绑定。它应该说Item 1Item 2...等等。它不会引发任何类型的错误。
    • 最奇怪的是,正如我刚刚注意到的,在{{item}} 之后添加一个空表达式{{}} 实际上暂时解决了这个问题。这肯定看起来像一个错误。
    • @Tympanix 用 plunker 演示检查我的更新答案..希望它现在清楚..
    • 我现在明白了。非常聪明的解决方案。 Maximum call stack exceed error 没有被扔进 JSFiddle,这就是我感到困惑的原因。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多