[英]How to execute a Angular controller method when I have its name as a string
In my AngularJS controller I have an event handler which receives an argument. 在我的AngularJS控制器中,我有一个事件处理程序,它接收一个参数。 The argument has a method name as string, which I need to execute.
该参数有一个方法名称为字符串,我需要执行它。 How do I call the method in my controller?
如何在控制器中调用该方法?
I have seen this question & answer but it doesn't work for me on the controller. 我已经看到了这个问题和答案,但是在控制器上对我不起作用。 Here is my code
这是我的代码
The event is created by a directive which is a confirmation dialog. 该事件由一个指令创建,该指令是一个确认对话框。 Event fires when the user clicks Yes.
用户单击“是”时将触发事件。
app.directive('yesNoModal', function() {
return {
restrict: 'E',
scope: {
yesNoData: '=',
},
controller: function($scope) {
$scope.handleYes = function() {
$scope.$emit('clickedYes', { "yesNoData": $scope.yesNoData });
}
$scope.handleNo = function() {
$scope.$emit('clickedNo');
}
},
templateUrl: 'partials/templates/yes-no-modal.html',
}
})
Event handler 事件处理程序
$scope.$on('clickedYes', function(event, arg) {
console.log(arg)
window[arg.yesNoData.yesMethod]()
});
window[arg.yesNoData.yesMethod]
returns undefined
in my case. 在我的情况下,
window[arg.yesNoData.yesMethod]
返回undefined
。 I also tried with $window
but I get undefined for the same. 我也尝试了
$window
但我没有得到相同的定义。 The function with the name of value of arg.yesNoData.yesMethod
variable is defined in the controller as a method and the value of yesNoData
is set before the modal is loaded. 在控制器中将名称为
arg.yesNoData.yesMethod
变量的值的arg.yesNoData.yesMethod
定义为方法,并在加载模式之前设置yesNoData
的值。 On clicking Yes in the modal the event is handled 在模式中单击“是”时,将处理事件
function deleteRequirement() {
console.log("In delete requirement")
}
使用$scope[arg.yesNoData.yesMethod]()
代替window[arg.yesNoData.yesMethod]()
因为它是$scope
对象而不是window
对象中的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.