AngularJS nested controllers

When you are new to Angular it can seem very confusing. One thing that gets especially perplexing is scope, where variables in your project can be accessed. This post looks at nested controllers and how that affects scope and we also look at whether they are passed by reference or by value between controllers.

We’ll use a very simplistic example:

Here we have defined the name variable in the parent and displayed it in both parent and nested controllers. What you will notice is any variable in the parent is automatically available to the child. However, be careful, if you are passing anything that isn’t an object then it is passed by value so if you try and change its value within the nested controller that change doesn’t propagate to the parent.

Now lets look at a different example, encapsulating that name variable into an object:

You will now notice that when you edit the name, both the nested controller and the parent controller are updated. This is because objects are always passed by reference, so in summary anything you want to persist between controllers should be encapsulated within an object first.

Read More