html:
<!doctype html>
<html ng-app="app">
<head>
</head>
<body>
<div ng-controller="MyCtrl">
<greeting aa="sayHello(name)"></greeting><br>
<greeting aa="sayHello(name)"></greeting><br>
<greeting aa="sayHello(name)"></greeting><br>
</div>
<script src="angular.min.js"></script>
<script src="js/cc.js"></script>
</body>
</html>
js:
var app = angular.module('app', []);
app.controller('MyCtrl', function($scope){
$scope.sayHello = function(name) {
alert("Hello"+name);
}
})
app.directive("greeting", function(){
return {
scope: {
greet: '&aa'
},
restrict: "AE",
template: '<input type="text" ng-model="username"><br><button ng-click="greet({name:username})">click</button>'
}
});
首先,scope中的@aa匹配html中的aa的内容(是个方法),然后将greet指向sayHello,参数绑定了input的内容username,将name的值指向username,点击按钮调用方法。