![](/img/trans.png)
[英]How to check which checkbox is checked and save the data into database using Angular
[英]how to count the checkbox which was checked using angular?
在这里,我使用$ watch显示计数器值。
但是计数器值还没有增加,
算一下
$scope.$watch('items', function(items){
var selectedItems = 0;
angular.forEach(items, function(item){
selectedItems += item.selected ? 1 : 0;
})
$scope.selectedItems = selectedItems;
}, true);
在用户界面中,
<div class="col-sm-4" ng-repeat="item in items">
<label class="chkbox-holder cbox mbot10" for="List-{{$index}}"><input ng-model="item.Selected" type="checkbox" id="List-{{$index}}"><label for="List-{{$index}}"></label>{{item.name}}</label>
</div>
要显示计数器值,
<div>Selected Items Length: {{selectedItems}}</div>
但计数器仍为0;
来自http服务的JSON值是,
[
{
"id": 1,
"refCode": "",
"name": "pragadees"
},
{
"id": 2,
"refCode": "",
"name": "pragadees"
}......]
任何人都可以帮忙。
您刚遇到错字错误。 您的标记绑定到item.Selected
而JavaScript正在检查item.selected
。 重命名它们可以解决您的问题。 我建议在ot html内使用小写键。
<input ng-model="item.selected" type="checkbox" id="List-{{$index}}">
^-- See here
首先,您的ng模型中有一个错字,是item.selected
不是item.Selected
这就是为什么它不匹配的原因...
这就是我将如何使用基本角度双向数据绑定,没有额外的计数器,手表,触发器等来编写它。
angular.module('myApp', []); angular.module('myApp').controller('Ctrl', ['$scope', function($scope) { $scope.items = [{ name: "Doe" }, { name: "Adam" }, { name: "Ado" }, { name: "Brown" }, { name: "Heather" }, { name: "Stan" }]; $scope.itemsSelected = function() { return $scope.items.filter(function(i) { return i.selected }).length; } } ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp" ng-controller="Ctrl"> <h2>current active selected options {{ itemsSelected() }}</h2> <ul> <div ng-repeat="item in items"> <label for="List-{{$index}}"> <input ng-model="item.selected" type="checkbox" id="List-{{$index}}"> <label for="List-{{$index}}"></label>{{item.name}}</label> </div> </ul> </body>
您可以改用ng-change :
var app = angular.module("app", []); app.controller("myCtrl", function($scope) { $scope.items = [ {name: 'A', value: 'a'}, {name: 'B', value: 'b'}, {name: 'C', value: 'c'}, {name: 'D', value: 'd'}, {name: 'E', value: 'e'} ]; $scope.counter = 0; $scope.change = function(e) { if(e){ $scope.counter +=1; }else{ if($scope.counter > 0) $scope.counter -=1; } }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="myCtrl"> <div class="col-sm-4" ng-repeat="item in items"> <label class="chkbox-holder cbox mbot10" for="List-{{$index}}"> <input ng-model="item.Selected" type="checkbox" id="List-{{$index}}" ng-change="change(item.Selected)"> <label for="List-{{$index}}"></label>{{item.name}}</label> </div> Counter: {{counter}} </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.