1. 程式人生 > >關於angular中指令呼叫controller的方法:&

關於angular中指令呼叫controller的方法:&

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,點選按鈕呼叫方法。