AngularJS Scoping (by value – by ref)

It is important to remember that you are basically working with Javascript.  No one would expect the following code to update the outer variable name:

var names = ["Misko", "Igor", "Vojta"];
function doubleName(name) {
  name = name + name;
}
for(var i=0;i<10;i++) {
  doubleName(names[i]);
}
This is because strings are passed by value in JavaScript.  So this is equivalent to
<div ng-init='names = ["Misko", "Igor", "Vojta"]'>
  <div ng-repeat='name in names'>
    <div ng-init="name = name + name"></div>
  </div>
  {{names}}
</div>
Objects on the other hand are passed by reference so this does work:
var objs = [{ name: "Misko"}, {name: "Igor"}, {name:"Vojta"}];
 function doubleName(obj) {
   obj.name = obj.name + obj.name;
 }
 for(var i=0;i<10;i++) {
 doubleName(obj[i]);
 }
Which is equivalent to:
<div ng-init='objs = [{name:"Misko"}, {name:"Igor"}, {name:"Vojta"}]'>
  <div ng-repeat='obj in objs'>
    <div ng-init="obj.name = obj.name + obj.name"></div>
  </div>
  {{objs}}
</div>

2 thoughts on “AngularJS Scoping (by value – by ref)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>