Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 565
Erik Honn Avatar asked Sep 18 '13 14:09

Erik Honn


People also ask

What does $scope mean in AngularJS?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).

What is the difference between $scope and scope?

The $ in "$scope" indicates that the scope value is being injected into the current context. $scope is a service provided by $scopeProvider . You can inject it into controllers, directives or other services using Angular's built-in dependency injector: module.

What is the number of scopes allowed in an AngularJS application?

Each AngularJS application has exactly one root scope, but may have any number of child scopes.


1 Answers

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 model var model = $parse(the_string);  // Assigns a value to it model.assign($scope, 42);  // Apply it to the scope // $scope.$apply(); <- According to comments, this is no longer needed  console.log($scope.life.meaning);  // logs 42 
like image 96
Erik Honn Avatar answered Oct 28 '22 15:10

Erik Honn