<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script src="../vendor/angular/angular.js"></script>
<script src="app/index.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="testController">
<div book-list></div>
<div>
<book-add></book-add>
</div>
</div>
</div>
</body>
</html>
angular.module('myApp', [])
.directive('bookList', function() {
return {
restrict: "ECAM",
controller: function($scope) {
console.log($scope);
},
controllerAs: "bookListController",
template: '<ul><li ng-repeat="books in bookList">{{books.name}}</li></ul>',
replace: true,
link: function(scope, iElement, iAttrs, bookListController) {
}
}
})
.directive('bookAdd', function() {
return {
restrict: "ECAM",
template: "<button>添加</button>",
replace: true,
controller: function($scope) {
this.addBook = function() {
alert("test");
$scope.$apply(function() {
$scope.bookList.push({
name: "世界百科"
})
})
}
},
link: function(scope, iElement, iAttrs, bookListController) {
console.log(bookListController, "大声地说");
iElement.on("click", bookListController.addBook);
}
}
})
.controller('testController', function($scope) {
$scope.bookList = [{
name: "PHP"
},
{
name: "JAVA"
},
{
name: "NET"
}, {
name: "WEB"
}
]
})
效果展示: