作用
link函数的作用与controller
差不多,同样可以像controller
中一样绑定绑定事件和属性,甚至参数也是参数多的,他一共有四个参数,前三个参数与controller
相同,这里说一下第四个参数
- 如果当前的指令有
require
,那么第四个参数就是require
引用的作用域 - 如果当前的指令没有
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>
效果
- 通过效果图我们可以发现在
link
函数中可以访问到controller
中的任何属性 - 模板中使用的方法也可以在
link
中 - 一般我们躲在
controller
中定义复用的行为,在link中定义当前组件使用的数据