问题
HTML view with directive:
<div click aaa="aaa()" action="action"></div>
Controller: I like to pass function bbb() in $scope.action:
app.controller('MainCtrl', function($scope) {
$scope.aaa = function () { alert('aaa'); }
$scope.bbb = function () { alert('bbb'); }
$scope.action = 'bbb()';
});
Directive:
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?'
}
});
I don't know how to evaluate action
to be replaced with bbb()
.
here is plunker: http://plnkr.co/edit/d8DtsNARKPPJwk2SO2WJ
回答1:
$scope.action
needs to be a pointer to $scope.bbb
and not just a string that refers to it loosely. "bbb()
in the controller means nothing, while $scope.bbb()
is what you created and need to use. When you're in HTML, $scope
is implied, which is why you can get away with simply writing aaa()
.
In your template and your HTML, you also need to call action
, just as you are calling 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;
});
来源:https://stackoverflow.com/questions/16234766/how-to-pass-ng-click-executable-action-in-variable-into-directive