AngularJS passes the name of the scope variable as a function parameter

Hi, I'm still new to AngularJs and wondered if this is possible.

On my controller, I am trying to create a function that takes a string parameter that will indicate which of $ http.get to call. Then I would like to assign this parameter in my area. for instance

$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"

therefore, the result will be placed and saved in the field $ scope.account and / or $ scope.contact.

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

+6
source share
2 answers

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

 $scope[partialtype]; 
+7
source

While it seems possible, I would suggest creating a custom Angular service that encapsulates your logic for HTTP requests. Then you can enable your service in your controller and access the functions of your service.

Take a look at the Angular documentation for creating custom services here: Angular Documentation for services

0
source

Source: https://habr.com/ru/post/980276/


All Articles