如何使用AngularJS将字符串作为函数执行?

时间:2015-11-19 00:08:12

标签: javascript angularjs

我定义了这两个函数:

CMtmp

我从前面传递了一个np.mean(CMtmp,axis=1)和一个字符串(' X'或者' Y'是我希望最终用户传递给我的)结束。我有这个代码,它处理字符串传递时:

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

话虽如此,给定一个包含字符串的变量,如何调用具有字符串变量名称的函数?

2 个答案:

答案 0 :(得分:2)

您应该使用以下内容选择正确的方法:

fix = lambda q: ({ k: '...' if k == 'ids' else fix(v) for k, v in q.items() }
                 if isinstance(q, dict) else
                 ([fix(i) for i in q] if isinstance(q, list) else q))

可以像:

一样使用
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]

答案 1 :(得分:1)

您可以将这两个函数封装在一个对象中,并在您的方法中调用此服务,如此

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

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