2015-11-19 89 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

相关问题