I have a string I have gotten from a routeParam
or a directive attribute or whatever, and I want to create a variable on the scope based on this. So:
$scope.<the_string> = "something".
However, if the string contains one or more dots I want to split it and actually "drill down" into the scope. So 'foo.bar'
should become $scope.foo.bar
. This means that the simple version won't work!
// This will not work as assigning variables like this will not "drill down"
// It will assign to a variables named the exact string, dots and all.
var the_string = 'life.meaning';
$scope[the_string] = 42;
console.log($scope.life.meaning); // <-- Nope! This is undefined.
console.log($scope['life.meaning']); // <-- It is in here instead!
When reading a variable based on a string you can get this behavior by doing $scope.$eval(the_string)
, but how to do it when assigning a value?
If you are ok with using Lodash, you can do the thing you wanted in one line using _.set():
https://lodash.com/docs#set
So your example would simply be:
_.set($scope, the_string, something);
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff