简体   繁体   English

AngularJS将范围变量名称作为函数参数传递

[英]AngularJS pass a scope variable name as a function parameter

Hi I'm still new to AngularJs and was wondering if this was possible. 嗨,我还是AngularJs的新手,想知道这是否可行。

On my controller, I'm trying to create a function that takes a string parameter that will indicate which $http.get to call. 在我的控制器上,我正在尝试创建一个函数,该函数接受一个字符串参数,该参数将指示要调用的$ http.get。 I would then like to assign that parameter in my scope. 然后我想在我的范围中分配该参数。 For example 例如

$scope.getpartial = function(partialtype) {
    var promise = "";
    switch(partialtype) {
        case "account":
             promise = $http.get("account url here");
             break;
        case "contact":
             promise = $http.get("contact url here");
             break;
    }
    promise.then(function(payload) {
        $scope.XXXXXXX = payload.data;
    });
}

Where XXXXXXX = partialtype == "account" or "contact" 其中XXXXXXX = partialtype ==“account”或“contact”

so the result would be placed and stored under $scope.account and/or $scope.contact. 所以结果将被放置并存储在$ scope.account和/或$ scope.contact下。

Is this possible or is there a better way to do this? 这是可能的还是有更好的方法来做到这一点?

由于$scope只是一个具有属性的对象,因此您可以使用括号表示法:

$scope[partialtype];

While this seems like it is possible, I would suggest creating a custom Angular service that encapsulates your logic for http requests. 虽然这似乎是可能的,但我建议创建一个自定义的Angular服务,它封装了http请求的逻辑。 You could then include your service in your controller, and access the functions in your service. 然后,您可以在控制器中包含您的服务,并访问服务中的功能。

Take a look at the Angular documentation for creating custom services here: Angular Documentation for Services 请在此处查看用于创建自定义服务的Angular文档服务的角度文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM