问题描述
带有指令的HTML视图:
HTML view with directive:
<div click aaa="aaa()" action="action"></div>
控制器:我想在$ scope.action中传递函数bbb():
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()';
});
指令:
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()
.
I don't know how to evaluate action
to be replaced with bbb()
.
这里是朋克: http://plnkr.co/edit/d8DtsNARKPPJwk2SO2WJ
推荐答案
$scope.action
需要是指向$scope.bbb
的指针,而不仅仅是一个松散地引用它的字符串.控制器中的"bbb()
毫无意义,而$scope.bbb()
是您创建并需要使用的内容.当您使用HTML时,暗含$scope
,这就是为什么您只需编写aaa()
就可以摆脱困境的原因.
$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()
.
在模板和HTML中,还需要调用action
,就像调用aaa
一样.
In your template and your HTML, you also need to call action
, just as you are calling aaa
.
HTML
<div ng-app="app" ng-controller="MainCtrl">
<div click aaa="aaa()" action="action()"></div>
</div>
JavaScript
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;
});
这篇关于如何将变量中的ng-click可执行操作(&)传递给指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!