Reputation: 372
Hello guys i have question, why is that the ng-model in my checkbox is not working inside the controller.
index.html :
<body ng-controller="MainCtrl">
<legend>UI</legend>
<div>
<input type="checkbox" ng-model="checkbox" />
</div>
{{checkbox}}
{{message}}
my script.js :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.checkbox = true;
if($scope.checkbox) {
$scope.message = "hello world!";
} else {
$scope.message = "Not Hello World!";
}
});
my goal is to change the message when the checkbox is change its Boolean value. But somehow in my index.html the checkbox binding is working it changes to true and false every time i clicked the checkbox but somehow the message is not changing. what seems to be wrong here? thanks
Upvotes: 1
Views: 34
Reputation: 3266
Looks like you've missed adding module ng-app
to the view, due to which the document is not getting compiled, the Controller is not getting instantiated.
For message to change every time checkbox is toggled, you need to change the message every time, you can use ng-change directive which triggers every time check box is toggled.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.checkbox = true;
$scope.message = "hello world!"
$scope.onChange = function() {
if ($scope.checkbox) {
$scope.message = "hello world!";
} else {
$scope.message = "Not Hello World!";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
<legend>UI</legend>
<div>
<input ng-change="onChange(checkbox)" type="checkbox" ng-model="checkbox" />
</div>
<p>{{checkbox}}</p>
<p>{{message}}</p>
Upvotes: 0
Reputation: 5067
Your code that checks the condition $scope.checkbox
is executed only once when the controller is created so the message
will never change. You can either do
<pre>
checkbox = {{checkbox}}
checkbox?'hello world!':'Not Hello World!' = {{checkbox?'hello world!':'Not Hello World!'}}
</pre>
or if you need it bound to a model, create a function which is called on change of the checkbox with ng-change
:
<input type="checkbox" ng-model="checkbox" ng-change="onChange(checkbox)"/>
and
$scope.onChange = function(checkbox) {
if(checkbox) {
$scope.message = "hello world!";
} else {
$scope.message = "Not Hello World!";
}
}
See plunker
Upvotes: 0