Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value in angular's $parse

Tags:

angularjs

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';
like image 308
xiankai Avatar asked Sep 14 '15 02:09

xiankai


1 Answers

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

like image 79
Phil Avatar answered Nov 16 '22 01:11

Phil