如何在指令中插入 $compile'd HTML 代码而不会出现 $digest 递归错误? [英] How to insert $compile'd HTML code inside the directive without getting $digest recursion error?

查看:22
本文介绍了如何在指令中插入 $compile'd HTML 代码而不会出现 $digest 递归错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a directive that, depending on the ng-repeat item data (from the database), build custom HTML with a switch case:

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() 迭代达到.中止!.我该如何处理?

the code above works, but the bindable {{step.title}} inside the function doesn't work. I tried $compile(html)($scope) but it gave me a Error: 10 $digest() iterations reached. Aborting!. How am I supposed to deal with this?

推荐答案

答案是为每个选项创建一个子"指令,这样你就可以通过值绑定它们,而不是用参数调用函数.你离开了程序 Javascript,但程序 Javascript 不会离开你

The answer is to create a "sub" directive for each opt, so you can bind them by value instead of calling functions with arguments. You leave procedural Javascript, but procedural Javascript doesn't leave you

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

这篇关于如何在指令中插入 $compile'd HTML 代码而不会出现 $digest 递归错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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