angularJS 自定义指令间的相互交互

angularJS 自定义指令间的相互交互

angularJS 自定义指令

  • transclude:当元素标签需要嵌套时使用,与ng-transclude配合使用。默认值为false不能使用嵌套,true为可以使用嵌套。在哪个标签上使用ng-transclude就在哪个标签内进行嵌套。
    代码示例:(将hello、hi标签进行替换同时span标签嵌套div内)
<script type="text/javascript">
    var m = angular.module('myApp',[]);
    m.directive('hello',function(){
        return{
            restrict:'E',
            replace:true,
            transclude:true,
            template:'<div>hello angular<h1 ng-transclude></h1></div>'
        };
    });
    m.directive('hi',function(){
        return{
            restrict:'E',
            replace:true,
            template:'<span>hi angular</span>'
        };
    });
    m.controller('Aaa',['$scope',function($scope){
        $scope.name='hello';
    }]);
    </script>

<body ng-controller="Aaa">
    <hello>
        <hi></hi>
    </hello>
</body>

页面结果展示:
这里写图片描述

在自定义指令当中controller与link的区别:
link是指DOM操作,操作也是针对当前标签
controller是多调用性的数据共享,指令与指令间进行交互时也可以设置一些方法数据,在其他标签中也可以调用

  • require:从外部引入数据,参数为被引入的指令,被引入的指令需要在引入指令的身上。
    》^:是指被引入的指令是引入指令的父级
    》?:兼容错误
    代码示例:
    <script type="text/javascript">
    var m = angular.module('myApp',[]);
    m.directive('hello',function(){
        return{
            restrict:'E',
            replace:true,
            transclude:true,
            controller:function($scope){
                //$scope.name='miaov';只能在该标签中使用
                this.name = 'miaov';//可以在其他标签中调用
            },
            template:'<div>hello angular<h1 ng-transclude></h1></div>'
        };
    });
    m.directive('hi',function(){
        return{
            restrict:'E',
            replace:true,
            require:'?^hello',//从外部引入指令,参数为被引入的标签
            link:function($scope,element,attr,reController){
                console.log(reController.name);
            },
            template:'<span>hi angular</span>'
        };
    });
    m.controller('Aaa',['$scope',function($scope){
        $scope.name='hello';
    }]);
    </script>

<body ng-controller="Aaa">
    <hello>
        <hi></hi>
    </hello>
</body>

页面结果展示:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值