Scoping scope (Mini-challenge 2)

Mini-challenge 2

ng-challengeAngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

We have an Angular application with two nested controllers, the requirement is that when the user input a text into the TextBox the “user” variable get updated in both places where it is bound in the view, but when we entering text into the input text, only one “user” variable gets updated. You can see the JsFiddle below:

This is the View:

<div ng-controller="navCtrl">
<div>navCtrl text: {{user}}</div>
<div ng-controller="loginCtrl">
<div> loginCtrl text: {{user}}</div>
        <input ng-model="user"></input>
   </div>
</div>

In the controller we use the scope  to bind the “user” variable

This is the controllers:

var myApp = angular.module('myApp', []);

myApp.controller('navCtrl', function ($scope) {
      $scope.user = "";
});

myApp.controller('loginCtrl', function ($scope) {

});

 

Here is a jsfiddle with the code.:

The problem is that only loginCtrl’s “user” variable is getting updated. The challenge consist in find a solution to this problem.

 

Here you can find a possible solution

If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.