创建复杂指令就是指令的嵌套,还有父子指令之间的通信,实现的效果如下
调用指令的页面代码:
<testbox data="val">
<test data="按钮1">
</test>
<test data="按钮2">
</test>
<test data="按钮3">
</test>
</testbox>
你选中了{{val}}
可以看到在testbox 里面 调用了 test 指令
test.html:
<!DOCTYPE html>
<html>
<head lang="en">
<script src="angular.min.js"></script>
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="test-app">
<div ng-Controller="test">
<!-- <div style="border: 1px solid red">
<test is-Checked="checked1"></test>
<div>{{checked1?"你选中了":"你没选中"}}</div>
</div>
<div style="border: 1px solid red">
<test is-Checked="checked2"></test>
<div>{{checked2?"你选中了":"你没选中"}}</div>
</div>
<div style="border: 1px solid red">
<test is-Checked="checked3"></test>
<div>{{checked3?"你选中了":"你没选中"}}</div>
</div>-->
<testbox data="val">
<test data="按钮1">
</test>
<test data="按钮2">
</test>
<test data="按钮3">
</test>
</testbox>
你选中了{{val}}
</div>
<script>
var app=angular.module('test-app', []);
app.controller("test",function($scope){
})
</script>
<script src="widget.js"></script>
</body>
</html>
tpl.html
<div ng-click="switch()" style=" box-sizing: border-box; overflow: hidden; width: 80px;height: 30px;background:#fff; border:1px solid {{isChecked?'#22DD48':'#ccc'}} ; border-radius: 10px;">
<div style=" float: left; width: 50%;height: 100%;background: {{isChecked?'#fff':'#ccc'}} ;">
</div>
<div style="float: right; width: 50%;height: 100%;background: {{isChecked?'#22DD48':'#fff'}} ;">
</div>
</div>
tpl1.html
<div style="border: 1px solid red;">
<ng-transclude></ng-transclude>
</div>
widget.js:
/**
* Created by start on 2016/6/24.
*/
(function(){
app.directive('test', function() {
return {
require:"^testbox",
restrict: 'E',
templateUrl:"tpl.html",
replace: true,
scope:{
data:"@"
},
link :function($scope,$element,attrs,testbox){
testbox.push($scope);
$scope.switch=function(){
$scope.isChecked=!$scope.isChecked
testbox.sw($scope);
}
}
};
});
app.directive('testbox',function(){
return{
restrict: 'E',
transclude:{
},
scope:{
data:"="
},
templateUrl: "tpl1.html",
replace: true,
controller: function($scope, $element, $attrs) {
var tests = $scope.tests = [];
this.push=function(test){
tests.push(test);
}
this.sw=function(test){
if(test.isChecked){
$scope.data=test.data
tests.forEach(function(val){
if(val.$id!=test.$id){
val.isChecked=false;
}
})
}else{
$scope.data="";
}
}
}
}
});
})();
核心思想就是
1、使用在父指令里面使用<ng-transclude></ng-transclude>来显示指令内部嵌套的内容
2、父指令在controller方法里面注册想要暴露给子指令调用的方法
3、子指令使用require指明对父指令的依赖,ng会自动把父指令的controller对象注入到子指令的link方法中
4、子指令在link方法中调用父指令暴露的方法把子指令的$scope对象传递到父指令中