如何在指令中插入 $compile 的 HTML 代码而不出现 $digest 递归错误?

2024-05-02

我有一个指令,根据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!。我该怎么处理这个问题?


答案是为每个选项创建一个“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){
   }   
  }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在指令中插入 $compile 的 HTML 代码而不出现 $digest 递归错误? 的相关文章

随机推荐