Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert $compile'd HTML code inside the directive without getting $digest recursion error?

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

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?

like image 891
pocesar Avatar asked Apr 15 '26 06:04

pocesar


1 Answers

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){
   }   
  }
});
like image 177
pocesar Avatar answered Apr 17 '26 09:04

pocesar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!