Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This problem has eluded me for a while and I couldn't find an answer here on SO, so now that I solved it I thought I would put it here in case someone else has the same problem as me and can't find help.

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! It is not there.

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?

share|improve this question

1 Answer

up vote 0 down vote accepted

This is 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:

var the_string = 'life.meaning';
var model = $parse(the_string);  // Get the model
model.assign(scope, 42);  // Assigns a value to it
scope.$apply();  // Apply it to the scope
console.log(scope.life.meaning);  // Logs 42
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.