Joe82 Joe82 - 1 year ago 122
AngularJS Question

Angular JS - key inside an object as variable

I have a variable defined, and a scope in order to apply a filter in Angular:

var tochange = "Ferrari";
$scope.filter = { cars :{ tochange : true}};

I would like the
variable inside the scope to change when I change its value outside the scope, but with this code it doesn't work as expected. You can check the JSfiddle here

Edit: changed the jsfiddle url, now it should work ok.


Answer Source

You can use bracket notation to use a variable as a key, but you have to declare the object separately (unless you can use some ES6 syntax)

var tochange = "Ferrari";
var obj = {};
obj[tochange] = true;
$scope.filter = { cars : obj};

Or ES6:

$scope.filter = { cars :{ [tochange] : true}};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download