【问题标题】:How to insert $compile'd HTML code inside the directive without getting $digest recursion error?如何在指令中插入 $compile'd HTML 代码而不会出现 $digest 递归错误?
【发布时间】:2013-04-29 11:10:10
【问题描述】:

我有一个指令,根据 ng-repeat 项目数据(来自数据库),使用 switch case 构建自定义 HTML:

app.directive('steps', function($compile){
  return {
    'restrict': 'A',
    'template': '<h3>{{step.name}}</h3><ul ng-repeat="opt in step.opts"><div ng-bind-html-unsafe="extra(opt)"></div></ul>',
    'link': function($scope, $element){
       $scope.extra = function(opt){
         switch ($scope.step.id){
           case 1:
             return "<div>Some extra information<select>...</select></div>"
           case 2:
             return "<div><input type='checkbox' ng-model='accept'> Accept terms</div>"
           case 3:
             return "<div>{{step.title}}<select multiple>...</select></div>"
        }
       }
    }
  }
});

上面的代码有效,但函数内部的可绑定{{step.title}} 无效。我试过$compile(html)($scope),但它给了我Error: 10 $digest() iterations reached. Aborting!。我该如何处理?

【问题讨论】:

  • 我认为这不是解决问题的正确“角度”方式。与其调用extra函数,不如有一个更大的模板,用ng-switch之类的来改变要显示的内容不是更清楚吗?
  • UI 数据来自数据库,完全依赖于数据库。这是一个“计划组合”选择器的表单向导,它会随着用户的变化而变化

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


【解决方案1】:

答案是为每个 opt 创建一个“sub”指令,这样您就可以按值绑定它们,而不是调用带参数的函数。你离开了程序 Javascript,但程序 Javascript 不会离开你

app.directive('opt', function($compile){
   return {
   'restrict': 'A',
   'template': '<div>{{extra}}</div>',   
   'link': function($scope, $element){
     switch ($scope.step.id){
       case 1:
         extra = "<div>Some extra information<select>...</select></div>";break;
       case 2:
         extra = "<div><input type='checkbox' ng-model='accept'> Accept terms</div>";break;
       case 3:
         extra = "<div>{{step.title}}<select multiple>...</select></div>";break;
     }

     $scope.extra = $compile(extra)($scope);
   }
  }
});

app.directive('steps', function(){
   return {
   'restrict': 'A',
   'template': '<h3>{{step.name}}</h3><ul><li ng-repeat="opt in step.opts" opt></li></ul>',
   'link': function($scope, $element){
   }   
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-21
    • 2015-02-27
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多