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

标签 javascript 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);
    });
};

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

最佳答案

您应该使用如下方式选择正确的方法:

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/

相关文章:

javascript - "NULL"值被添加到 localStorage 数组中

javascript - 自动进度条

javascript - 无法在 AngularJS 中运行动画演示

angularjs - 在 Angular-fullstack 中加载 local.env.js

javascript - 如何忽略 typescript 中的 "Cannot find name ' M'“错误?

javascript - AngularJS - 如何在多个实例中限制 ngClick 的范围

javascript - 如何将 Flask 的 JSON 传递给 Javascript

javascript - 将数据从 MVC Controller 传递到 Angular View ,而不在最终 html 中显示数据值

javascript - 在 AngularJS 中设置应用程序范围的 HTTP header

javascript - 带有 ngHide 的 ngAnimate 无法添加 'ng-hide-animate' Hook 类