Skip to content Skip to sidebar Skip to footer

How To Execute String As A Function Using AngularJS?

I have these two functions defined: function fetchYPosts() { $http.get('/postsY/') .then(function(response) { self.posts = response.data; }, function(response)

Solution 1:

You should select the correct method using something like this:

var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;

which can be used like:

self.handler = function(id, XOrY) {
    var fetcher = XOrY == 'x' ? fetchXPosts : fetchYPosts;
    $http.post("/" + XOrY + "/" + id + "/handle/")
    .then(function(response) {
        fetcher();
        # Here is where I want to call funcitonToCall.
    }, function(response) {
        self.cerrorMessages = BaseService.accessErrors(response.data);
    });
};

If you have a situation where there's just too many different fetching functions, you can instead define them like this as part of a hash:

var fetch = {

  YPosts: function() {
    $http.get("/postsY/")
    .then(function(response) {
        self.posts = response.data;
    }, function(response) {
        self.posts = {};
    }); 
  },

  XPosts: function() {
    $http.get("/postsX/")
    .then(function(response) {
        self.posts = response.data;
    }, function(response) {
        self.posts = {};
    }); 
  }

}

and grab the function from fetch[XorY]:

self.handler = function(id, XOrY) {
    $http.post("/" + XOrY + "/" + id + "/handle/")
    .then(function(response) {
        fetch[XorY]();
        # Here is where I want to call funcitonToCall.
    }, function(response) {
        self.cerrorMessages = BaseService.accessErrors(response.data);
    });
};

Solution 2:

you can encapsule these two function in an object, and call this service in your method like this

   var service = {
     fetchXPosts: function(){},
     fetchYPosts: function(){}
   }

    self.handler = function(id, XORY) {
       service['fetch'+XORY+'posts']();
    }

Post a Comment for "How To Execute String As A Function Using AngularJS?"