3

我有一个指令,根据ng-repeat项目数据(来自数据库),使用开关盒构建自定义 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!. 我该怎么处理这个?

4

1 回答 1

3

答案是为每个 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){
   }   
  }
});
于 2013-04-29T03:10:10.360 回答