我有这个方法来获取所选对象的值,以及" .length"用于指示用户选择了多少个对象。但我希望有一个取消按钮并清除所有复选框并重置我的" .length"
$scope.selection = [];
$scope.toggleSelection = function toggleSelection(image) {
var idx = $scope.selection.indexOf(image);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(image);
}
$scope.totalitems = $scope.selection.length;
$scope.itemobject = {
'attachments': $scope.selection
};
这是我的重复:
<ul ng-repeat="image in images | filter:query as attachmensresults">
<li>
<div class="cbxdelete">
<input class="checkbx" id="ckBox" type="checkbox" value="{{image.id}}" ng-checked="selection.indexOf(image.id) > -1" ng-click="toggleSelection(image.id)" />
</div>
<a href="{{image._links.file.href}}" data-lightbox="example-set" data-title="Click the right half of the image to move forward.">
<div class="img-preview">
<img ng-src="{{image._links.file.href}}" alt="" />
</div>
</a>
</li>
</ul>
答案 0 :(得分:1)
为什么不是这样的?
<button ng-click="cancel()">Cancel</button>
$scope.cancel = function(){
$scope.selection = [];
$scope.totalitems = 0;
$scope.itemobject = { 'attachments': $scope.selection };
}
这会将您的选择数组重置为空,因此ng-checked将为false。
答案 1 :(得分:0)
您还可以向selected
数组添加images
属性。这样可以更轻松地更改模型,因为您可以使用ng-model="image.selected"
双向绑定。
要清除所有必须循环每个图像。 循环所有项目可能比你的代码慢一点,但我认为代码更少,更容易阅读。
你不应该在ng-repeat(id="ckBox"
)中使用id。因为ID在页面中应该是唯一的。
请查看下面的演示或jsfiddle。
如果您需要将所选图像作为单独的阵列,则可以使用map
创建新阵列。请参阅方法post
作为示例。
angular.module('demoApp', [])
.controller('mainController', MainController);
function MainController($filter) {
var vm = this,
changeAll = function(state) {
angular.forEach(vm.images, function(image, index) {
image.selected=state;
});
};
this.images = [
{id: 1, url: 'http://lorempixel.com/400/200/sports/1/',selected: false},
{id: 2, url: 'http://lorempixel.com/400/200/sports/2/',selected: false},
{id: 3, url: 'http://lorempixel.com/400/200/sports/3/',selected: false}
];
this.cancel = function() {
changeAll(false);
};
this.selectAll = function() {
changeAll(true);
};
this.post = function() {
var mapped = vm.images.map(function(image,index) {
return {
id: image.id,
selected: image.selected
};
});
alert($filter('json')(mapped));
}
}
MainController.$inject = ['$filter'];
&#13;
ul {
list-style-type: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as main">
<button ng-click="main.post()">send</button>
<button ng-click="main.selectAll()">all</button>
<button ng-click="main.cancel()">cancel</button>{{main.images|json}}
<ul ng-repeat="image in main.images">
<li>
<div class="cbxdelete">
<input class="checkbx" type="checkbox" value="{{image.id}}" ng-model="image.selected" />
</div>
<a href="{{image.url}}" data-lightbox="example-set" data-title="Click the right half of the image to move forward.">
<div class="img-preview">
<img ng-src="{{image.url}}" alt="" />
</div>
</a>
</li>
</ul>
</div>
&#13;