如何执行字符串使用AngularJS功能? [英] How to execute string as a function using AngularJS?

查看:108
本文介绍了如何执行字符串使用AngularJS功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义这两个函数:

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

我通过了 ID 和一个字符串('X'或'Y'是我想要的最终用户传递给我的)从前端。我有这个code的字符串传递它处理:

I am passed an id and a string ('X' or 'Y' is what I want the end-user to pass to me) from the front-end. I have this code which handles when the string is passed:

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

随着中说,考虑到其中包含字符串的变量,我怎么调用它具有字符串变量的名称的功能?

With that said, given a variable which holds a string, how do I call the function which has the name of the string variable?

推荐答案

您应该使用像这样选择正确的方法:

You should select the correct method using something like this:

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

可使用的,如:

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 = {};
    }); 
  }

}

抢取函数[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);
    });
};

这篇关于如何执行字符串使用AngularJS功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆