Setting dynamic scope variables in AngularJs - scope.<some_string>
The solution I have found is to use $parse.
"Converts Angular expression into a function."
If anyone has a better one please add a new answer to the question!
Here is the example:
var the_string = 'life.meaning';// Get the modelvar model = $parse(the_string);// Assigns a value to itmodel.assign($scope, 42);// Apply it to the scope// $scope.$apply(); <- According to comments, this is no longer neededconsole.log($scope.life.meaning); // logs 42
Using Erik's answer, as a starting point. I found a simpler solution that worked for me.
In my ng-click function I have:
var the_string = 'lifeMeaning';if ($scope[the_string] === undefined) { //Valid in my application for first usage $scope[the_string] = true;} else { $scope[the_string] = !$scope[the_string];}//$scope.$apply
I've tested it with and without $scope.$apply. Works correctly without it!