AngularJS and checkboxes

138 views Asked by At

I'm learning AngularJS and play around with it a little.

I have now a little understanding problem with checkboxes. Here is my JavaScript code:

angular.module('app',[]).controller('MainCtrl',function($scope,$http)
{
    $scope.photo = 1;
    $scope.art = 0;

    $scope.change = function()
    {
         $scope.photo = 0;
         $scope.art = 1;
    }
});

and HTML:

<div ng-controller="MainCtrl">
    <div class="checkbox">
         <label><input type="checkbox" ng-checked="photo">PhotoGallery</label>
    </div>
    <div class="checkbox">
        <label><input type="checkbox" ng-checked="art">Art</label>
    </div>

    <button ng-click="change()">change</button>
</div>

And I created a little jsfiddle to show my problem:

http://jsfiddle.net/q30nrkzy

When you run this code you see Photogallery pre selected. Now when I click on the change button it changes the selection. But when I then remove the "art" selection and click on the change button again, nothing happens.

Is this correct or did I understand something completely wrong?

2

There are 2 answers

0
sebastienbarbier On BEST ANSWER

ng-checked will update your IHM on load but clicking on a checkbox will not update your $scope.variables since you do not define them as a model. Just add ng-model to get a two-way data binding and it should works.

<div class="checkbox">
    <label>
        <input type="checkbox" ng-checked="photo" ng-model="photo">PhotoGallery</label>
</div>
<div class="checkbox">
    <label>
        <input type="checkbox" ng-model="art" ng-checked="art">Art</label>
</div>

Here is a working exemple : updated jsfiddle

1
xavier hans On

The problem is that you change the value in a n only one way in your function change.

You can do it like that I think:

$scope.photo = 1;
$scope.art = 0;

$scope.change = function() {
    tmp = $scope.photo;
    $scope.photo = $scope.art;
    $scope.art = tmp;
}