Angularjs - 使用指令实例化其他指令?

时间:2013-01-28 13:03:21

标签: javascript angularjs

让我们说在我的HTML中我有这样的东西:

<tabcontent></tabcontent>

然后这个指令的javascript是这样的:

tabsApp.directive('tabcontent', function(){

  var myObj = {
    priority:0,
    template:'<div></div>',
    replace: true,
    controller: 'TabCtrl',
    transclude: false,
    restrict: 'E',
    scope: false,
    compile: function (element, attrs){
      return function (parentScope, instanceEle){
        parentScope.$watch('type', function(val) {
          element.html('<div '+val+'></div>');
        });
      }
      $compile(parentScope);
    },
    link: function postLink(scope, iElement, iAttrs){}
  };
  return myObj;

});

正确解析HTML,并在控制器JS中找到type的值。

so <tabcontent></tabcontent> is replaced with <div recipe></div> for example..

(那部分确实发生了)

所以我也有食谱指令:

tabsApp.directive('recipe', function(){

  var myObj = {
    priority:0,
    template:'<div>TESTING</div>',
    replace: true,
    controller: 'TabCtrl',
    transclude: false,
    restrict: 'E',
    scope: false,
    compile: function (element, attrs){
      return {
        pre: function preLink(scope, iElement, iAttrs, controller){},
        post: function postLink(scope, iElement, iAttrs, controller){}
      }
    },
    link: function postLink(scope, iElement, iAttrs){}
  };
  return myObj;

});

这显然非常简单,仅用于测试。但是配方指令没有被处理......

这是怎么回事?

1 个答案:

答案 0 :(得分:19)

你需要改变两件事:

  1. recipe指令不得限于 E (元素)。如果要生成<div recipe></div>之类的指令,则必须至少将 A (属性)添加到指令配置的restrict属性中:

    app.directive('recipe', function() {
       return {
          restrict: 'E',
          ...
    
  2. 您需要在'watch'之后编译tabcontent指令的HTML内容:

    app.directive('tabcontent', function($compile){
       return {    
       ...    
       link: function (scope, iElement, iAttrs) {
                scope.$watch('type', function(val) {
                   iElement.html('<div '+val+'></div>');           
                   $compile(iElement.contents())(scope);         
                 });
             }
       ...        
    
  3. jsFiddle http://jsfiddle.net/bmleite/n2BXp/