我定義這兩個函數:如何使用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」是我想要的最終用戶傳遞給我什麼)從前端。我有這樣的代碼,當字符串傳遞它處理:,
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);
});
};
這一說給持有字符串的變量,我該怎麼稱呼它具有字符串變量的名稱的功能?
看起來像一個XY問題。你爲什麼要這樣做? – elclanrs
@elclanrs我在前端有兩個對象(XPosts和YPosts)。每篇文章都有一個按鈕。該按鈕應該發佈到URL'/ {{X或Y}}/id/handle',然後調用'fetch {{XorY}}()'。 – user2719875