1

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 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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;
}

1 Comment

How would you do it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.