问题
Is it possible to do this in angular? When I press one single button element, other button elements automatically get disabled. I saw a similar question but looking for this in pure angularjs.
<html ng-app>
<button ng-model="button" > abc </button>
<button ng-disabled="button"> def </button>
<button ng-disabled="button"> ghi </button>
</html>
回答1:
You can bind an ng-click event to all three of the buttons, passing an identifier to the function (i.e. the id of the button. Your function would then bind a variable to the scope, which you could then use to determine if ng-disabled should be active or not.
For example, in your controller you would have something similar to:
$scope.selectedButton;
$scope.selectButton = function(id) {
$scope.selectedButton = id;
}
Then, in your HTML; you would revise it to take in the ng-click and ng-disabled considerations mentioned above.
<html ng-app ng-controller="SomeController">
<button ng-disabled="selectedButton && selectedButton != 'abc'" ng-click="selectButton('abc')">abc</button>
<button ng-disabled="selectedButton && selectedButton != 'def'" ng-click="selectButton('def')">def</button>
<button ng-disabled="selectedButton && selectedButton != 'ghi'" ng-click="selectButton('ghi')">ghi</button>
</html>
Note, the logic of checking if selectedButton and the selectedButton does not equal foo, is to determine that a button has been selected, thus the variable is set to scope.
回答2:
Simple, pure angular way.
<html ng-app>
<button ng-click="buttonsDisabled = true"> abc </button>
<button ng-disabled="buttonsDisabled"> def </button>
<button ng-disabled="buttonsDisabled"> ghi </button>
</html>
http://jsfiddle.net/HB7LU/21811/
回答3:
<html ng-app="yourApp">
<body ng-controller="buttonCtrl">
<button ng-disabled="!button1" ng-click="toggleFunction(1)" > abc </button>
<button ng-disabled="!button2" ng-click="toggleFunction(2)" > abc </button>
<button ng-disabled="!button3" ng-click="toggleFunction(3)" > abc </button>
</body>
</html>
<script>
yourApp.controller('buttonCtrl', ['$scope', function($scope) {
function toggleFunction(activeBtn){
if (activeBtn == 1){
$scope.button1 = true;
$scope.button2 = false;
$scope.button3 = false;
} else if (activeBtn == 2){
$scope.button1 = false;
$scope.button2 = true;
$scope.button3 = false;
} else if (activeBtn == 3){
$scope.button1 = false;
$scope.button2 = false;
$scope.button3 = true;
}
}
}]);
</script>
回答4:
You can do it like this
<script>
var app=angular.module('myApp', []);
app.controller('someCtrl',function($scope){
$scope.mySwitch=true;
$scope.toggle=function(){
$scope.mySwitch=!$scope.mySwitch;
};
});
</script>
<div ng-app="myApp">
<div ng-controller="someCtrl">
<p>
<button ng-click="toggle()">abc</button>
</p>
<p>
<button ng-disabled="mySwitch">def</button>
<button ng-disabled="mySwitch">ghi</button>
</p>
</div>
</div>
来源:https://stackoverflow.com/questions/34621350/how-can-i-disable-other-buttons-when-i-press-one-button-in-angularjs