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

Angularjs - Using directive to instantiate other directives?

本文关键字:指令 实例化 其他 Angularjs      更新时间:2023-09-26

所以让我们在我的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 中找到。

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

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

这是怎么回事?

您需要更改 2 件事:

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

jsFiddle: http://jsfiddle.net/bmleite/n2BXp/