1、expander.html:
<!DOCTYPE HTML>
<html ng-app="app">
<head>
<title>单击展开demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/bootstrap.css">
<script src="../js/angular.js"></script>
<style>
.expander{width: 250px;border: 1px solid black;}
.expander>.title{background: black;color: white;padding: .1em .3em;cursor: pointer;}
.expander>.body{padding: .1em .3em;}
</style>
</head>
<body>
<div ng-controller="someCtrl">
<expander class='expander' expander-title='title'>
{{text}}
</expander>
</div>
<script src="./expander.js"></script>
</body>
</html>
2、expander.js:
var myModule = angular.module("app",[]);
myModule.directive('expander',function(){
return {
restrict:'AE',
replace:true,
transclude:true,
scope:{
title:'=expanderTitle'//这里绑定的是expander-title属性,而且经测试非要转成这样的小驼峰写法才可
//=传递的是指令标签内属性expander-title值'title'的值'点击展开'($scope.title = '点击展开';)
},
template:'<div>'
+'<div class="title" ng-click="toggle()">{{title}}</div>'
+'<div class="body" ng-show="showme" ng-transclude></div>'
+'</div>',
link:function(scope,element,attrs){
scope.showme = false;
scope.toggle = function(){//每次点击调用此方法都让scope.showme值反转1次
scope.showme = !scope.showme;
}
}
}
});
myModule.controller('someCtrl', ['$scope', function($scope){
$scope.title = '点击展开';//这里的title是expander-title='title'中的'title'值部分的赋值;而上面指令定义中的scope{title:是template:模板中的{{title}},也就是说在指令中,title:'=expanderTitle'这句话的意思是将属性expander-title的值'title'(由控制器赋值)绑定独立作用域也就是指令内的作用域——模板中的{{title}}之上,让{{title}}和'title'同值。记住:独立作用域三大绑定策略的作用就是绑定同一个标签内的属性名传值.不同的是:@符传递是属性值字串;=号传递的是属性值的值(控制器赋予);&符传递是的属性调用的方法()
$scope.text = '这里是展开后的内容';
}]);