如何在AngularJS组件的控制器中访问已包含的内容?

时间:2018-07-06 14:34:52

标签: angularjs angularjs-components

我有一个带有多个插入槽的组件,如下所示:

  angular.module('myApp').component('myComponent', {
    controller: myComponentCtrl,
    controllerAs: 'vm',
    templateUrl: 'template.html',
    transclude : {
      transclude1: '?transcludeOne',
      transclude2: '?transcludeTwo',
    },
    bindings: {
      // bindings here
    }
  });

  myComponentCtrl.$inject = ['$element', '$timeout', '$transclude',];

  function myComponentCtrl($element, $timeout, $transclude) {
    var vm = this,

    $transclude(function(clone, scope, futureParent, slot) {
       console.log('$transclude was called');
       console.log('clone:', clone);
       console.log('scope:', scope);
       console.log('futureParent:', futureParent);
       console.log('slot:', slot);
       // I want to know the content of the transclusion slot

    });

  }

如果运行此命令,控制台将显示:

$transclude was called
clone: w.fn.init []
scope: b {$$childTail: null, $$childHead: .......
futureParent: undefined
slot: undefined

我想要获得的是透明插槽的内容,所以如果我的组件是这样使用的:

<my-component>
  <transclude-one><span>This is transclude one</span></transclude-one>
  <transclude-two><span>This is transclude two</span></transclude-two>
</my-component>

我希望我的控制器知道第一个插槽的内容,在这种情况下为<span>This is transcluded slot one</span>。 我试图为此使用$ transclude函数,但是我找不到办法,而且文档对此也不是很清楚。

https://code.angularjs.org/1.5.0/docs/api/ng/service/ $ compile#-controller-

文档提及参数

  

function([scope],cloneLinkingFn,futureParentElement,slotName):

,但是第3个和第4个参数始终为空。谁能告诉我如何使用$ transclude函数,以及能否实现所需的功能?

0 个答案:

没有答案