AngularJS checkbox odd behavior
-
21-12-2019 - |
Question
some friends and I are working on a project. This is the second project in which I am working with AngularJS, were currently using version 1.2.3.
Despite that I sometimes find some of its behavior odd, and don't understand why something is happening.
So the situation is this... I have in my cshtml file the followig:
<div class="checkbox">
<label>
<input name="somecheckbox" type="checkbox" ng-click="click()" ng-model="displayRegardlessOfSomething" />
<label>Display regardless of something</label>
</label>
</div>
<h1>{{displayRegardlessOfSomething}}</h1>
In my javascript file I have the following code inside a directive:
At the very beginning:
$scope.displayRegardlessOfSomething = true;
And I have the following:
$scope.click = function () {
console.log($scope.displayRegardlessOfSomething)
}
And whenever I check or uncheck the checkbox I always get true... However, the peculiar part is that the content inside the <h1></h1>
tags changes.... So, it's like I am changing the value of a variable on the html layer, but not on the JavaScript layer...
Why is this happening?
I have solved the problem by using $parent.displayRegardlessOfSomething but I don't understand why that fixed the problem... what caused the problem in the first place?
Solution
I tried what you did in the fiddle and it works fine for me.
http://jsfiddle.net/nicolasmoise/X9KYU/1/
The fact that it works for you when you used $parent
makes me think a parent controller is at fault here. Maybe you have two variables with the same names?
P.S. : remember that in Javascript, primitives are passed by value and objects are passed by reference. This is the cause of many mistakes for Angular developers. See this fiddle where I illustrate my point.
with primitives: http://jsfiddle.net/nicolasmoise/X9KYU/
with objects: http://jsfiddle.net/nicolasmoise/X9KYU/2/
OTHER TIPS
Unless you're pretty sure everything is living in the same scope, which is almost never, you should always have a dot somewhere in your ng-model expression.
myApp.controller('MyController2', function($scope) {
$scope.model = { displayRegardlessOfSomething: true };
$scope.click = function() {
console.log($scope.model.displayRegardlessOfSomething);
};
});
<input type="checkbox"
ng-click="click()"
ng-model="model.displayRegardlessOfSomething" />
See this plunker for details for live demo.