0

Here is my code:

<body ng-app="app">
<div ng-controller="TestController">
    <input type="checkbox" checked ng-repeat="num in array track by $index" ng-model="array[$index]" />
</div>
<script type="text/javascript">
    var app = angular.module('app', []);
    app.controller('TestController', function ($scope) {
        $scope.array = [1, 2, 3, 4];
    });
</script>

I especially add checked attribute to each <input> tag, for the checkbox could checked by default. But the result is none of the four checkbox is checked. Why?

I know if I add ng-checked="num" attribute could make the checked work, But I still wondering why the natural checked arrtibute doesn't work.

hh54188
  • 14,887
  • 32
  • 113
  • 184

4 Answers4

0

From angular docs

By default, ngModel watches the model by reference, not value.

When you say array[$index] it gives integer value which is you model name And its wrong

Please do it in this way

<div ng-controller="TestController">
    <input type="checkbox" checked ng-repeat="num in array track by $index" ng-model="array[$index].checked" title="{{array[$index].val}}" />
</div>
<script type="text/javascript">
    var app = angular.module('app', []);
    app.controller('TestController', function ($scope) {
        $scope.array = [{val:1,checked:true},{val:2,checked:false},{val:3,checked:true},{val:4,checked:true},{val:5,checked:false}];
    });
</script>
Community
  • 1
  • 1
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

ng-model="array[$index]" sets the dom checked property to false

Madis Pärn
  • 106
  • 5
0

You shouldn't combine checked with ng-model. Same applies for ng-checked with ng-model. Both modify the checkbox checked state which leads to unpredictable behavior.

If you want your checkbox to be checked by default do it via the ng-model directive.

The structure you are using seems a little bit weird. You checkboxes aren't checked because angular can't match the value.

By default using ng-model on a checkbox will yield true and false in the ng-model value when the user interacts with it. You can change that by using ng-true-value and ng-false-value. Check angular documentation.

If you add let's say ng-true-value="2" to your checkboxes then the second one will be initially selected because it starts with the value 2.

avladov
  • 851
  • 4
  • 12
0

As far as why checked doesn't work: when angular binds to the checkbox using either ng-checked or ng-model, it sets the checked attribute so that the checkbox looks correct in the browser - it doesn't care what the checked attribute is when it first binds.

Dave
  • 4,375
  • 3
  • 24
  • 30