我有一组boolean
变量,如果标记为false
,则会将其他变量切换为true
。
这种方法有干净的模式吗?考虑到boolean
变量的数量可能会增加。
angular.module("app", [])
.controller("controller", function($scope) {
$scope.a = true;
$scope.b = false;
$scope.c = false;
$scope.toggleA = function() {
$scope.a = true;
$scope.b = false;
$scope.c = false;
}
$scope.toggleB = function() {
$scope.b = true;
$scope.a = false;
$scope.c = false;
}
$scope.toggleC = function() {
$scope.c = true;
$scope.b = false;
$scope.a = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<button ng-click="toggleA()">A is {{a}}</button>
<button ng-click="toggleB()">B is {{b}}</button>
<button ng-click="toggleC()">C is {{c}}</button>
</div>
答案 0 :(得分:4)
根据使用方式的不同,可能会有很多解决方案,但是有几个相互依赖的变量似乎很疯狂。您应该使用一个可以包含两个以上值的变量来表示当前状态:
angular.module("app", [])
.controller("controller", function($scope) {
$scope.current = 'a';
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<button ng-click="current = 'a'">A is {{ current == 'a' }}</button>
<button ng-click="current = 'b'">B is {{ current == 'b' }}</button>
<button ng-click="current = 'c'">C is {{ current == 'c' }}</button>
</div>
&#13;
答案 1 :(得分:3)
为什么不简单地做这样的事情:
angular.module("app", [])
.controller("controller", function($scope) {
$scope.x = 'a';
$scope.toggle = function(x) {
$scope.x = x;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<button ng-click="toggle('a')">A is {{x === 'a'}}</button>
<button ng-click="toggle('b')">B is {{x === 'b'}}</button>
<button ng-click="toggle('c')">C is {{x === 'c'}}</button>
</div>
答案 2 :(得分:1)
'您可以使用数组作为布尔值的容器,然后只使用一个函数来切换它。这是一个例子。
angular.module("app", [])
.controller("controller", function($scope) {
$scope.keys = {
a: true,
b: false,
c: false
};
$scope.toggle = function(change_key) {
for (var key in $scope.keys)
if ($scope.keys.hasOwnProperty (key))
if (key === change_key)
$scope.keys[key] = true;
else
$scope.keys[key] = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<button ng-click="toggle('a')">A is {{keys.a}}</button>
<button ng-click="toggle('b')">B is {{keys.b}}</button>
<button ng-click="toggle('c')">C is {{keys.c}}</button>
</div>
答案 3 :(得分:0)
你可以尝试这个我不知道你的下一步是什么,但它可以是一个很好的解决方案
angular.module("app", [])
.controller("controller", function($scope) {
$scope.keys = [
{"name":"a","value":true},
{"name":"b","value":false},
{"name":"c","value":false}
];
$scope.toggle = function(key) {
key.value = !key.value;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
<button ng-repeat="key in keys" ng-click="toggle(key)">{{key.name}} is {{key.value}}</button>
</div>
&#13;