温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

angularJS如何实现自定义指令间的相互交互

发布时间:2021-08-04 14:18:58 来源:亿速云 阅读:104 作者:小新 栏目:web开发

小编给大家分享一下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<h2 ng-transclude></h2></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>

页面结果展示:

angularJS如何实现自定义指令间的相互交互

在自定义指令当中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<h2 ng-transclude></h2></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>

页面结果展示:

angularJS如何实现自定义指令间的相互交互

以上是“angularJS如何实现自定义指令间的相互交互”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI