AngularJS组件转换:如何在onInit中访问transclude变量?
解决AngularJS组件中访问transclude对象的问题
你在把旧指令转成组件时遇到的transclude访问问题很常见,毕竟组件和指令的API设计有差异。别担心,我们可以通过依赖注入$transclude服务来搞定这个需求。
完整的组件实现代码
angular.module('Module').component('myComponent', { transclude: { slotA: '?slotA' }, controller: ['$transclude', function($transclude) { this.$onInit = function() { this.isFilled = $transclude.isSlotFilled('slotA'); }; }] });
关键说明
- 组件的controller需要注入
$transclude服务,它提供了和指令link函数中transclude参数完全一致的API,包括你需要的isSlotFilled方法。 - 组件中使用
this(组件实例)替代了指令中的scope,所以我们把isFilled绑定到this上,这样模板中就能直接通过组件实例访问这个属性。 - 注意钩子函数的正确名称是
$onInit(带美元符号),这是AngularJS组件标准的初始化钩子,你之前写的onInit会不生效哦。
如果你用ES6类语法
如果项目用了ES6类来写组件控制器,注入方式可以这样调整:
class MyComponentCtrl { constructor($transclude) { this.$transclude = $transclude; } $onInit() { this.isFilled = this.$transclude.isSlotFilled('slotA'); } } // 显式注入避免压缩问题 MyComponentCtrl.$inject = ['$transclude']; angular.module('Module').component('myComponent', { transclude: { slotA: '?slotA' }, controller: MyComponentCtrl });
内容的提问来源于stack exchange,提问作者Guillaume
相关产品推荐
相关产品推荐

