3

带有指令的 HTML 视图:

<div click aaa="aaa()" action="action"></div>

控制器:我喜欢在 $scope.action 中传递函数 bbb():

app.controller('MainCtrl', function($scope) {
    $scope.aaa = function () { alert('aaa'); }
    $scope.bbb = function () { alert('bbb'); }

    $scope.action = 'bbb()';
});

指示:

app.directive('click', function () {
    return {
        scope: {
            aaa: '&',
            action: '&'
        },
        template: 
            '<button ng-click="aaa()">show aaa (work ok)</button>' +
            '<button ng-click="action">show bbb (not work)</button>' +
            '<br>How to pass ng-click action in variable into directive?'
    }
});

我不知道如何评估action以替换为bbb().

这是 plunker:http ://plnkr.co/edit/d8DtsNARKPPJwk2SO2WJ

4

1 回答 1

6

$scope.action需要是一个指针,$scope.bbb而不仅仅是一个松散地引用它的字符串。 "bbb()在控制器中没有任何意义,而$scope.bbb()您创建并需要使用的是什么。当你在 HTML中时$scope,这是隐含的,这就是为什么你可以简单地编写aaa().

在您的模板和 HTML 中,您还需要调用action,就像调用aaa.

http://jsfiddle.net/DFcJf/

HTML

<div ng-app="app" ng-controller="MainCtrl">
    <div click aaa="aaa()" action="action()"></div>

</div>

JavaScript

var app = angular.module('app', []);

app.directive('click', function () {
    return {
        scope: {
            aaa: '&',
            action: '&'
        },
        template: 
            '<button ng-click="aaa()">show aaa (work ok)</button>' +
            '<button ng-click="action()">show bbb (not work)</button>' +
            '<br>How to pass ng-click action in variable into directive?'
    }
});
app.controller('MainCtrl', function($scope) {
    $scope.aaa = function () { alert('aaa'); }
    $scope.bbb = function () { alert('bbb'); }

    $scope.action = $scope.bbb;
});
于 2013-04-26T11:14:42.917 回答