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

标签 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,并在 Controller 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. recipe指令不得限于 E(元素)。如果您正在生成类似 <div recipe></div> 的指令,您必须至少将 A(属性)添加到 restrict指令配置的属性:

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

    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/

关于javascript - Angularjs - 使用指令来实例化其他指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562679/

相关文章:

javascript - 如何添加到 Vue Class Bindings 的数量?

angularjs - 我可以将Restangular.extendModel或extendCollection与嵌套资源路由一起使用吗?

javascript - Angular2测试异步Http.MockBackend.connections promise 不会产生

javascript - 纯 JavaScript - 编辑 DOM 元素中的文本而不触及子元素

javascript - 在 PHP 中创建 onchange/oninput 监听器

javascript - 与 Angular JS 中使用指令类似和不同

javascript - Angular 嵌套 Controller 访问 ng-repeat 数据

angularjs - Ionic/Angular 自定义页面过渡

javascript - React 中输入元素的怪癖

javascript - 获取部分 html 表单外部站点