2015-11-19 36 views
1

我定義這兩個函數:如何使用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); 
    }); 
}; 

這一說給持有字符串的變量,我該怎麼稱呼它具有字符串變量的名稱的功能?

+0

看起來像一個XY問題。你爲什麼要這樣做? – elclanrs

+0

@elclanrs我在前端有兩個對象(XPosts和YPosts)。每篇文章都有一個按鈕。該按鈕應該發佈到URL'/ {{X或Y}}/id/handle',然後調用'fetch {{XorY}}()'。 – user2719875

回答

2

你應該使用這樣的選擇正確的方法:

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

} 

and grab從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); 
    }); 
}; 
+0

我用你提供的第二種方式,因爲它看起來更乾淨,更舒適。由於某種原因,我注意到速度有所不同(比'fetch [XOrY]()'明顯慢於'fetchPosts()'),但除此之外,這很好。 – user2719875

1

,你可以在一個對象encapsule這兩種功能,在你的方法調用這個服務這樣

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

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

謝謝。只是爲了驗證,'.call(service,id)'是做什麼的?考慮到我的'fetchXPosts'和'fetchYPosts'函數不需要'id'參數,'service''fetch'+ XORY +'posts']'就足夠了嗎? – user2719875

+0

ok,那麼你不需要調用,你可以使用'service''fetch +'XORY'+ posts']()'來執行函數,當你想綁定函數'this'的上下文時會使用調用。 – Sean

相關問題