Joe82 Joe82 - 3 months ago 12
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
tochange
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.

Thanks!

Answer

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}};
Comments