简体   繁体   中英

AngularJs ng-repeat is register two click event on checkboxes?

https://jsfiddle.net/ytygc19t/2/

HTML:

<div ng-app="app" ng-controller="MainCtrl">
  <span>Test App @ </span> status:{{loaded}}
<hr>

  <div ng-repeat="checkbox in checkBoxArray track by $index">{{checkbox}}
    <input name="x{{checkbox}}"  id="x{{checkbox}}" ng-click="removeCheckBox(checkbox)" type="checkbox"/>
  </div>
</div>

JS:

angular.module("app",[])
.controller("MainCtrl", ["$scope", "$timeout", function($scope, $timeout){
   $scope.checkBoxArray = ["a", "b", "c", "d", "e"]
   $scope.loaded = "loaded";

   $scope.removeCheckBox = function (value){
      $timeout(function(){
         $scope.checkBoxArray.splice($scope.checkBoxArray.indexOf(value), 1);
      }, 300)       
   }
}])

When i check checkbox a, a is removed, and b is also checked

Remove track by $index because everytime a is selected, then a is removed and that time b index will become 1 so it is getting checked.

Find the working fiddle here : https://jsfiddle.net/varit05/ytygc19t/3/

Hope it helps you!

Cheers!

I think what you're experiencing is a clash between HTML checkbox functionality and Angular functionality. Try tracking the checkbox value using angular.

<li ng-repeat="item in Items">
  <label>{{item.Name}}
    <input type="checkbox" ng-model="item.Selected" ng-click="item.Selected = true" />
  </label>
</li>

And in the controller

$scope.Items = [{Name: 'bla', Selected: false}, ...]

Also, is there any particular reason you need ? That could be giving you some problems as well.

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