8

I have a string reference to one of my scope values like this:

var reference_string = "form.name";

And I want to assign a value to the object it is referencing:

$scope.form.name = 'newvalue';

Looking around, I found 2 possible solutions: using plain JS or using the angular $parse function.

However, it seems like the $parse function only returns the value. Can I make it so that I can assign a new value?

ie. I want to do something like

var reference_string = "form.name";
var reference = getReference($scope, reference_string); // ideally using an angular in-built function like $parse
reference = 'newvalue'; // should have the same effect as $scope.form.name = 'newvalue';
7
  • Are you trying to use strings to access an object like form['name'] ? Commented Sep 14, 2015 at 2:35
  • @TjGienger yeah, except that its in a nested format so I can't do it directly. $scope['form.name'] won't work Commented Sep 14, 2015 at 2:41
  • did you try $scope['form']['name'] ? I never have, just a thought Commented Sep 14, 2015 at 2:43
  • use regex to separate the original string Commented Sep 14, 2015 at 2:43
  • @TjGienger Short of using eval, I can't do that. Also I mentioned that there was a plain JS way (through parsing the string and traversing the object), which is a little hacky and I was hoping for a more elegant solution with angular's $parse. Commented Sep 14, 2015 at 2:48

2 Answers 2

25

The object returned by $parse has an assign() method for setting values.

var getter = $parse(reference_string);
getter.assign($scope, 'newValue');

Plunker demo ~ http://plnkr.co/edit/RlhXRpJvQ69ZdEkstyq8?p=preview

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! The example really helped to show how to use it.
If the reference has multiple data {name1 : "test1",name2 : "test2"} How does it works with this scenario...@Phil
@VenkatRJV not sure what you mean. $parse only supports a single expression AFAIK but you can create multiple assignment strings for the same object
@Phil where did you get avatar like that? just curious :)
-1

$parse is an Angular service which converts an expression into a function. The function can then be invoked and passed a context (usually scope) in order to retrieve the expression's value. In addition, if the expression is assignable the returned function will have an assign property. The assign property is a function that can be used to change the expression's value on the given context.

enter link description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.