我定义了这两个函数:
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”是我希望最终用户传递给我的)。我有这段代码在传递字符串时进行处理:
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);
});
};
话虽如此,给定一个包含字符串的变量,我如何调用具有字符串变量名称的函数?
最佳答案
您应该使用如下方式选择正确的方法:
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);
});
};
如果您遇到的情况是有太多不同的获取函数,您可以像这样将它们定义为散列的一部分:
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 = {};
});
}
}
并从 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);
});
};
关于javascript - 如何使用 AngularJS 将字符串作为函数执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792972/