Angular ngModel binding on first level method of $scope

This is not exactly a question with some code, but more for my understandings. So please forgive me if this isnt appropriate here..

I was playing with a simple checkbox with an ngModel assigned:

<input type="checkbox" ng-model="someFlag"/>

I expect this to bind the boolean of the checkbox to $scope.someFlag (if controller and everything else configured properly). And yes, it does work. But there are times where I found that this is not working. Case: When I try to do something when the someFlag changes (for example in a $watch) the value is not really binded.

But then I came accross something a collegua at work mentioned once:

Use a wrapper object

Doing it like that works now without any problems:

<input type="checkbox" ng-model="wrapperObject.someFlag"/>

Watching $scope.wrapperObject.someFlag works as expected.

Now the question: Why??

Answers


When ngModel directive is executed, it reads attribute's ng-model value (in this case, "someFlag") and saves it in it's local function scope (not to confuse to angulars $scope). But since a boolean in javascript is a primitive, you cannot pass it by reference, only by value. That means only the $scope.someFlag's value (true or false) get's copied to ngModel, and not the way of accessing and modifying $scope.someFlag from ngModel.

When you use wrapper object, it is passed by reference, meaning, it is the same thing both in $scope.wrapperObject and in ngModel's local function scope, because it points to the same memory address behind the scenes.

I'm not sure if this explanatory enough, but when working with primitive values in angular, you must keep in mind the difference between passing by reference and by value and that when primitive's change, other parts of application might not know this.


Have a look to this video which is taken from Egghead.io, your problem is explained here.


Need Your Help

Return array without name from method

java arrays

I'm doing an assignment that requires me to complete the following block of code:

GUI C++ Qt with Visual Studio 2010

c++ visual-studio-2010 user-interface qt4

I'm developing a C++ application that needs a GUI. I would like to use the Windows 7 Ribbon Framework, so I'm not interested in having my app compatible with OS different that windows. I would like...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.