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?
Using Erik's answer, as a starting point. I found a simpler solution that worked for me.
In my ng-click function I have:
I've tested it with and without $scope.$apply. Works correctly without it!
The solution I have found is to use $parse.
If anyone has a better one please add a new answer to the question!
Here is the example:
Please keep in mind: this is just a JavaScript thing and has nothing to do with Angular JS. So don't be confused about the magical '$' sign ;)
The main problem is that this is an hierarchical structure.
This is undefined because "$scope.life" is not existing but the term above want to solve "meaning".
A solution should be
or with a little more efford.
Since you can access a structural objecte with
There are several good tutorials about this which guide you well through the fun with JavaScript.
There is something about the
Go and search the web for 'angular $apply' and you will find information about the $apply function. And you should use is wisely more this way (if you are not alreay with a $apply phase).
If you are using Lodash library below is the way to set a dynamic variable in the angular scope.
Create Dynamic angular variables from results
Just to add into alread given answers, the following worked for me:
HTML:
Where
$index
is the loop index.Javascript (where
value
is the passed parameter to the function and it will be the value of$index
, current loop index):