简体   繁体   中英

AngularJS $http.get passing variable as param key

I am new to AngularJS and trying to see if this is possible. I have looked at a lot of $http.get questions online but can't find an answer to this.

I have an api call that has three different parameter key possibilities.

$http.get(url, {params : {$scope.searchBy : $scope.value}})

$scope.searchBy is marked as a syntax error. It has 3 possible values from a dropdown list.

I tried var search = $scope.searchBy; but when I use {params : {search : $scope.value}} the value is "search" and not $scope.searchBy.

Any suggestions how this can be done without if statements and separate api calls?

Thank you.

You will have to do something like this as this is valid javascript syntax.

var paramValues = {};
paramValues[$scope.searchBy] = $scope.value;
return $http.get(url, {params: paramValues});

When you define an object using the syntax you have in your question the property/field name must be a known constant. If it is variable, which you want in this case, then you can create the object first and then set the value using the obj[propertyName] = someValue; notation.

Use property accessor bracket notation to construct the desired params object:

var config = { params: {} };
config.params[$scope.searchBy] = $scope.value;

$http.get(url, config);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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