require属性
例子:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div ng-app="myApp">
<div ng-controller="firstController">
<div book-list>
</div>
</div>
</div>
<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>
app/index.js
angular.module('myApp', [])
.directive('bookList', function () {
return {
restrict: 'ECAM',
controller: function ($scope) {
$scope.books = [
{
name: 'php'
},
{
name: 'javascript'
},
{
name: 'java'
}
];
this.addBook = function(){
$scope.$apply(function(){
$scope.books.push({
name:'Angularjs'
})
});
}
},
controllerAs:'bookListController',
template: '<div><ul><li ng-repeat="book in books">{{book.name}}</li></ul><book-add></book-add></div>',
replace:true
}
})
.directive('bookAdd',function(){
return {
restrict:'ECAM',
require:'^bookList',
template:'<button type="button">添加</button>',
replace:true,
link:function(scope,iElement,iAttrs,bookListController){
iElement.on('click',bookListController.addBook);
}
}
})
.controller('firstController', ['$scope', function ($scope) {
// console.log($scope);
}]);
Last updated