Setting dynamic scope variables in AngularJs - scope.<some_string> Setting dynamic scope variables in AngularJs - scope.<some_string> angularjs angularjs

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!


Create Dynamic angular variables from results

angular.forEach(results, function (value, key) {            if (key != null) {                           $parse(key).assign($scope, value);                                  }          });

ps. don't forget to pass in the $parse attribute into your controller's function