简体   繁体   中英

AngularJS: checked attribute in checkbox doesn't work

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.

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>

ng-model="array[$index]"将dom Checked属性设置为false

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.

至于为什么checked不起作用:当使用ng-checkedng-model将angular绑定到复选框时,它设置了checked属性,以便该复选框在浏览器中看起来正确-不在乎checked属性是什么是第一次绑定时。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM