directive之link

作用

link函数的作用与controller差不多,同样可以像controller中一样绑定绑定事件和属性,甚至参数也是参数多的,他一共有四个参数,前三个参数与controller相同,这里说一下第四个参数

  1. 如果当前的指令有require,那么第四个参数就是require引用的作用域
  2. 如果当前的指令没有require,那么第四个参数就是当前的controller 本身
    • 而在controller上面添加到this上面的属性和方法就可以通过第四个参数访问

代码

代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <h1>{{indexName}}</h1>
      <h2>{{childName}}</h2>
      <!-- 自定义组件 -->
      <hello-world></hello-world>
    </div>

    <script>
      var app = angular.module("myApp", []);
      app.controller("myCtrl", function ($scope) {
        $scope.indexName = "主页";
        $scope.childName = "父作用域";
      });
      app.directive("helloWorld",function(){
          return {
            restrict:'E',
            template:`
            <div>
              <div>{{linkName}}</div>
              <button ng-click="handleClick()">{{childName}}</button>
            </div>
            `,
            controller:function($scope){
              $scope.childName = "自定义组件"
              this.thisName = "this上的属性"
            },
            link:function(scope, elem, attrs, controller){
                console.log(scope.childName);
                console.log(controller);
                scope.linkName = "link中绑定的属性"
                scope.handleClick = function(){
                    alert("Hello World")
                }
            }
          }
      })
    </script>

  </body>
</html>

效果

在这里插入图片描述

  1. 通过效果图我们可以发现在link函数中可以访问到controller中的任何属性
  2. 模板中使用的方法也可以在link
  3. 一般我们躲在controller中定义复用的行为,在link中定义当前组件使用的数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值