6

Hi I'm still new to AngularJs and was wondering if this was possible.

On my controller, I'm trying to create a function that takes a string parameter that will indicate which $http.get to call. 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"

so the result would be placed and stored under $scope.account and/or $scope.contact.

Is this possible or is there a better way to do this?

2
  • This totally works, although it may not be best practice to use this method, in our SPA this is what we need. I don't know hot to mark this as an answer since this is a comment. Commented Dec 30, 2014 at 16:33
  • I posted a quick answer - was on mobile at the time when I commented. Commented Dec 30, 2014 at 16:40

2 Answers 2

7

Since $scope is just an object with properties, you can use bracket notation:

$scope[partialtype];
Sign up to request clarification or add additional context in comments.

Comments

0

While this seems like it is possible, I would suggest creating a custom Angular service that encapsulates your logic for http requests. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.