未选中时禁用按钮 AngularJS
Disable button when nothing checked AngularJS
我想仅在选中 modelCheck
时显示按钮 post,当没有 checked
时显示 disable
我的代码:HTML:
HTML:
<table>
<tr>
<th>name</th>
<th><button class="btn" ng-if="(modelCheck | json) != ({} | json)" ng-click="post()">post</button></th>
<th><button class="btn disabled" ng-if="(modelCheck | json) == ({} | json)" ng-click="post()">post</button></th>
</tr>
<tr ng-repeat="x in messages">
<td>{{x.name}}</td>
<td><input type="checkbox" ng-model="modelCheck[x.name]"/></td>
</tr>
</table>
JS:
$scope.modelCheck = {};
$scope.messages =
[
{
"name": "eva",
},
{
"name": "ben",
},
];
$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};
我的笨蛋:http://next.plnkr.co/edit/FudqIFQ1Pe0Vfhvq
提前感谢您的回答和帮助!
您可以使用 ng-disabled 来执行此操作。
<button class="btn" ng-disabled="!isSelected()" ng-click="post()">post</button>
并在 JavaScript 中:
$scope.isSelected = function() {
var cnt = 0;
Object.keys($scope.modelCheck).forEach(function (e) {
if ($scope.modelCheck[e]) {
cnt + = 1;
}
});
if (cnt > 0) {
return true;
}
else {
return false;
}
}
Plunker demo。希望这有帮助
我想仅在选中 modelCheck
时显示按钮 post,当没有 checked
时显示 disable
我的代码:HTML:
HTML:
<table>
<tr>
<th>name</th>
<th><button class="btn" ng-if="(modelCheck | json) != ({} | json)" ng-click="post()">post</button></th>
<th><button class="btn disabled" ng-if="(modelCheck | json) == ({} | json)" ng-click="post()">post</button></th>
</tr>
<tr ng-repeat="x in messages">
<td>{{x.name}}</td>
<td><input type="checkbox" ng-model="modelCheck[x.name]"/></td>
</tr>
</table>
JS:
$scope.modelCheck = {};
$scope.messages =
[
{
"name": "eva",
},
{
"name": "ben",
},
];
$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};
我的笨蛋:http://next.plnkr.co/edit/FudqIFQ1Pe0Vfhvq
提前感谢您的回答和帮助!
您可以使用 ng-disabled 来执行此操作。
<button class="btn" ng-disabled="!isSelected()" ng-click="post()">post</button>
并在 JavaScript 中:
$scope.isSelected = function() {
var cnt = 0;
Object.keys($scope.modelCheck).forEach(function (e) {
if ($scope.modelCheck[e]) {
cnt + = 1;
}
});
if (cnt > 0) {
return true;
}
else {
return false;
}
}
Plunker demo。希望这有帮助