简体   繁体   English

AngularJs ng-repeat是在复选框上注册两次单击事件吗?

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

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

HTML: 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: 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 当我选中复选框a时,a被删除,b也被选中

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. track by $index删除track by $index因为每次选择a时,都将删除a,而此时b索引将变为1,因此将对其进行检查。

Find the working fiddle here : https://jsfiddle.net/varit05/ytygc19t/3/ 在这里找到可用的小提琴: 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. 我认为您遇到的是HTML复选框功能和Angular功能之间的冲突。 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 track by $index ? 此外,是否有任何特定原因需要您按$ index进行跟踪 That could be giving you some problems as well. 那也可能给您带来一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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