简体   繁体   中英

AngularJS/Rails $http.post data field name as variable

I am trying to send some data from angular directive to rails controller using POST method. I wonder if it is possible to have data field name as variable. Example:

   var URL = null;
   var fieldName = null;

   if(something) {
     URL = ...;
     fieldName = ...;
   } else {
     URL = ...;
     fieldName = ...;
   }

   $http({
     url: URL,
     method: 'POST',
     data: { fieldName : c.$modelValue}
   })

Now my POST parameters are: "fieldName" => "(correct value from c.$modelValue)". I want field name to be fieldName value. Thank you in advance.

I guess you look for something like:

   var URL = null;
   var fieldName = null;
   var data = {};

   if(something) {
     URL = ...;
     fieldName = ...;
   } else {
     URL = ...;
     fieldName = ...;
   }
   data[fieldName] = c.$modelValue;

   $http({
     url: URL,
     method: 'POST',
     data: data
   })

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