我想在选择一个或多个复选框值时启用提交按钮,我尝试使用下面的代码启用按钮,但是如果我检查一个值,它会使所有复选框都被选中?知道什么是错误的吗?
main.html中
<tr ng-repeat="user in userList track by $index">
<td st-ratio="20">{{user.attuid}}</td>
<td st-ratio="30">{{user.firstName}} {{user.lastName}}</td>
<td st-ratio="20"><input type="checkbox" ng-model="userList.selected" ng-click="checkedValue(user)"> </td>
</tr>
<button class="btn btn-primary" ng-disabled="user.selected" ng-disabled="!userList.selected" ng-click="addUsers()">Add User(s)</button>
Ctrl.js
$scope.$on('show-user-list',function(e,data){
$scope.userList = data;
$scope.userList.selected = false;
});
$scope.checkedValue = function(user) {
user._id = user.attuid;
user.type = 'user';
if ($scope.selectedUsers.indexOf(user) === -1) {
$scope.selectedUsers.push(user);
$scope.userList.selected = true;
} else {
$scope.selectedUsers.splice($scope.selectedUsers.indexOf(user), 1);
}
console.log($scope.userList.selected);
};
答案 0 :(得分:1)
创建单个范围变量以使用ng-disabled进行评估。像$ scope.userSelected之类的东西。根据选择/取消选择的用户更新它。
<强>控制器强>
$scope.userSelected = false;
$scope.checkedValue = function() {
$scope.userSelected = false;
angular.forEach($scope.userList, function(user) {
if (user.selected) {
$scope.userSelected = true;
}
});
};
<强> HTML 强>
<table>
<tr ng-repeat="user in userList track by $index">
<td st-ratio="20">{{user.attuid}}</td>
<td st-ratio="30">{{user.firstName}} {{user.lastName}}</td>
<td st-ratio="20">
<input type="checkbox" ng-model="user.selected" ng-click="checkedValue()"> </td>
</tr>
</table>
<button class="btn btn-primary" ng-disabled="!userSelected" ng-click="addUsers()">Add User(s)</button>
这是一个有效的plunk
答案 1 :(得分:0)
问题是您的复选框值为ng-model="userList.selected"
,因此所有复选框都具有相同的值userList.selected
,因此当您选中其中一个时,所有复选框都会被选中。
更新 - (处理禁用和启用adduser按钮)
我们如何$scope.selectedUsers
然后根据其长度ng-disabled="selectedUsers.length == 0"
示例代码段:
angular.module("myApp", [])
.controller("myCtrl", function($scope) {
$scope.userList = [{
attuid: "1",
firstName: "abc",
lastName: "xyz",
selected: false
}, {
attuid: "2",
firstName: "abc",
lastName: "xyz",
selected: false
}];
$scope.selectedUsers = [];
$scope.checkedValue = function(user) {
user._id = user.attuid;
user.type = 'user';
if ($scope.selectedUsers.indexOf(user) === -1) {
$scope.selectedUsers.push(user);
$scope.userList.selected = true;
} else {
$scope.selectedUsers.splice($scope.selectedUsers.indexOf(user), 1);
}
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="user in userList">
<td st-ratio="20">{{user.attuid}}</td>
<td st-ratio="30">{{user.firstName}} {{user.lastName}}</td>
<td st-ratio="20">
<input type="checkbox" ng-model="user.selected" ng-click="checkedValue(user)">
</td>
</tr>
</table>
<button class="btn btn-primary" ng-disabled="selectedUsers.length == 0" ng-click="addUsers()">Add User(s)</button>
</div>