Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

how to parse a string to a function name in angularjs

I have a function like following :

vm.saveStep = function(service, method, data, formData, steps){
      service.update({}, data).$promise.then(function (res) {
        if(formData != null) {
          fileUploadService.create({}, formData).$promise.then(function (res) {
            steps.step2 = true;
          }).catch(function (err) {
            console.log('Error uploading files');
          });
        }
      }).catch(function (err) {
        console.log('Error saving data');
      });
    };

in this function I have the method argument, this argument can take two different String values 'create' and 'update'.

Inside this function I call the service.update() or service.create() depending on the method argument value.

The issue is that I don't know how to parse that string value so when I pass 'create' I call service.create() and when I pass 'update' I call service.update().

Edit:

I forgot to mention that when I pass 'update' I want to call service.update({}, data) and for 'create' I want to call service.create(data), notice {} in update function

what I mean my function will be like this :

vm.saveStep = function(service, method, formData, steps){ ..... }

and then when I pass 'create(data)' as a string I'll call service.create(data) and for 'update(data)' I'll call service.update({}, data)

Upvotes: 0

Views: 47

Answers (1)

Kenneth
Kenneth

Reputation: 28747

You can use the bracket syntax:

service[method](arg1, arg2, ...);

Alternatively, if you need different arguments, you can just do an if-statement:

if(method === "create"){
    service.create(arg1, arg2);
}else if (method === "update"){
    service.update(arg1);
}

Upvotes: 1

Related Questions