Javascript 如何从字符串值调用作用域上的函数
我有一个包含字符串数组的对象Javascript 如何从字符串值调用作用域上的函数,javascript,angularjs,angularjs-service,Javascript,Angularjs,Angularjs Service,我有一个包含字符串数组的对象 $scope.actions=[ "add_inscription", "add_tools", "add_instruction", "remove_inscription", "remove_tools", "remove_instruction" ]; 我希望能够通过授权功能进行动态动作调用 $scope.delegate = function () { var arg = arguments[0];
$scope.actions=[
"add_inscription",
"add_tools",
"add_instruction",
"remove_inscription",
"remove_tools",
"remove_instruction"
];
我希望能够通过授权功能进行动态动作调用
$scope.delegate = function () {
var arg = arguments[0];
for ( key in $scope.actions ) {
if ($scope.actions[key] == arg ) {
// call function that has a matching name
}
}
}
所以在我的模板中我有这样的东西
<button ng-click="delegate('add_inscription')">Add Inscription</button>
但在angular中,我无法完成此操作。假设您的“操作”函数是在范围内定义的,例如:
$scope.add_inscription = function(){ ... }
你应该做:
var _action = 'add_inscription';
$scope[_action]();
天哪,我真不敢相信,我一直在尝试,过去我已经用过了,但我完全忘了在$scope['add_deliting']]后面加上(),谢谢。如果我看不到那样的小事,我一定很累。我实际上是将函数名指定给范围变量。
var _action = 'add_inscription';
$scope[_action]();