简体   繁体   中英

How to call a function on the scope from a string value

I have an object containing an array of strings

$scope.actions=[
    "add_inscription",
    "add_tools",
    "add_instruction",
    "remove_inscription",
    "remove_tools",
    "remove_instruction"
];

and I would like to be able to do dynamic action calls through a delegating function..

$scope.delegate = function () {

    var arg = arguments[0];

    for ( key in $scope.actions ) {

        if ($scope.actions[key] == arg ) {

            // call function that has a matching name

        }
    }
}

So in my template I have something like this

<button ng-click="delegate('add_inscription')">Add Inscription</button>

I don't know if I am thinking in the right direction with this either,, but the point is that my actions object is actually pretty large and I don't want to write massive switch case statement that I will have to update all the time.

Is there a way to do this in angular?

I have no problem doing this in straight up javascript

var fnstring = "add_inscription";

// find object
var fn = window[fnstring];

// if object is a function
if (typeof fn === "function") fn();

but in angular I can't get this done..

assuming that your "actions" functions are defined inside the scope, like:

$scope.add_inscription = function(){ ... }

you should do:

var _action = 'add_inscription';
$scope[_action]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM