[AngularJS] Angular 1.5 $transclude with named slot

本文详细介绍了在Angular1.5版本中如何使用并检查transclude功能,包括如何通过控制器访问传入元素,以及如何使用named slot而非默认transclude来检查transclude元素是否被定义。

In Angular 1.5, there is no link and compile. So use if you transclude, you cannot access the fifth arguement in link function, which is transcludeFn.

 

But in v1.5, you can access $transclude in controller. 

And what you can do for that is check whether the transclude element is passed in or not. For that you also need to use named slot, not default transclude: true.

 

See example:

class ServiceListController {
    constructor($transclude) {
        this.$transclude = $transclude;
    }

    hasTransclude(){
        return this.$transclude.isSlotFilled('actions');
    }
}

const clmServiceListComponent = {
    bindings: {
       ...
    },
    transclude: {
        'actions': '?clmActions'
    },
    controller: ServiceListController,
    controllerAs: 'vm',
    template: require('./service-list.html')
};

export default (ngModule) => {
    ngModule.component('clmServiceList', clmServiceListComponent);
}
    

In the example, we has a directive call 'clmActions', and gave slot name as 'actions'.

So you can use:

this.$transclude.isSlotFilled('actions');

to check whether the transclude element is defined or not.

 

In HTML:

<clm-service-list>
      <clm-actions>
           <clm-action ></clm-action>
       </clm-actions>
</clm-service-list>

If we gave the clm-actions tag, the hasTransclude() function in controller will return 'true', if you remove clm-actions tag, the function will return false.

转载于:https://www.cnblogs.com/Answer1215/p/5384874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值