在将条件模板附加到body之前使用条件模板编译指令

时间:2015-01-14 14:10:18

标签: javascript angularjs angularjs-directive

假设我有条件模板的指令:

app.directive('postContent', function ($compile) {
  var template = ''
  var text = '<ANY>template for text</ANY>';
  var image = '<ANY>template for image</ANY>';
  var video = '<ANY>template for video</ANY>';
  var compiler = function ($element, $attrs) {
    if (condition1) {
     template = video;
    } else if(condition2) {
     template = image;      
    } else {
     template = text;
   }
  }

  var templateElem = angular.element(template);
  $element.after(templateElem);
  $element.remove();
  var subLink = $compile(templateElem);
  return {
    pre: function(scope, element, attrs) {
      subLink(scope);
    },
    post: function(scope, element, attrs) {
    }
  }

});

condition1和condition2过于复杂,无法在视图中实现。
如果condition1和condition2是静态的,这可以正常工作,但问题是,我使用的条件超出了范围,我没有编译器函数的作用域。我该怎么办?

1 个答案:

答案 0 :(得分:0)

首先,&#34;条件过于复杂&#34;可以在函数中抽象出来,或者计算一次并存储在变量中:

link: function(scope){
  scope.condition1 = doVeryComplicatedLogic();
  scope.condition2 = function(){
     return doAnotherComplicatedLogic(scope.param);
  }
}

模板:

<any ng-if="condition1">template for video</any>
<any ng-if="condition2()">template for image</any>
<any ng-if="!condition1 && !condition2()">template for text</any>

但是,如果你坚持,你可以在link函数中有条件地编译/链接模板:

link: function(scope, element){
   var tmpl = text; 
   if (condition1){
      tmpl = video;
   } else if (condition2){
      tmpl = image;
   }

   element.append(tmpl);
   $compile(element.contents())(scope);
}