简体   繁体   中英

Is it possible to pass $scope.value inside json object in Angularjs controller?

I have a var data with json object defined. I want to dynamically change json fields from html and call slightly different POST APIs. eg:

var data={
    $scope.value:'25',
    'speciality':$scope.speciality,
    'field2':'something',
    'field3':'something else'
}

How can I change $scope.value can have 10 to 15 different values. I tried doing,

var example=$scope.value;
var data={
  example:'25',
  'speciality':$scope.speciality,
  'field2':'something',
  'field3':'something else'
}
But this too doesn't work and sends example as json field.

Any help is apprciated. Thanks

No, you cannot have a key that dynamically changes. Your best bet is to build the object at the time you need it:

var obj = {};
obj[$scope.value] = 25;
...

If you want to use a variable as a property name, then you must create an object first, then assign the data using square bracket notation.

var data = {   
        'speciality':$scope.speciality,
        'field2':'something',
        'field3':'something else'
    }

data[$scope.value] ='25';
var data = {
    'field2':'something',
    'field3':'something else'
};
$scope.value.forEach(function(value) {
    data[value] = '25';
});

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