不多说,直接上代码
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>employee list</title>
<style type="text/css">
.main {
padding-left: 50px
}
ul,
li {
list-style: none;
padding: 0;
}
li {
width: 150px;
}
li .name {
cursor: pointer;
padding: 5px;
background: #82c082;
margin-bottom: 2px;
}
li .content {
padding-left: 15px;
}
</style>
</head>
<body ng-controller="listCtrl">
<div class="main">
<h3>employee list</h3>
<employee-list test-list="lists"></employee-list>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('listCtrl', function($scope) {
$scope.lists = [{
name: "Alice",
content: 'i\'m Alice',
visible: false
},
{
name: "Bella",
content: 'i\'m Bella',
visible: false
},
{
name: "John",
content: 'i\'m John',
visible: false
}
]
});
app.directive('employeeList', function() {
return {
restrict: 'E',
replace: true,
scope: {
lists: '=testList'
},
template: '<ul><li ng-repeat="list in lists"><div class="name" ng-bind="list.name" ng-click="toggle(list)"></div><div class="content" ng-bind="list.content" ng-show="list.visible"></div></li></ul>',
link: function(scope, ele, attrs) {
scope.toggle = function(list) {
scope.lists.map(function(item) {
if(list.name === item.name) {
list.visible = !list.visible;
alert(list.content);
} else {
item.visible = false;
}
})
}
}
}
})
</script>
</body>
</html>