Javascript angularJS中的多状态按钮式切换
我想在表中实现一个功能,用户可以通过点击来设置单元格的值。 可以说有3-4个状态,也可以附加一个ng模型 我在angularjs中寻找切换按钮,但它们只是开/关类型 简言之;单击按钮将设置值为:活动、非活动、排除 正在寻找具有多个状态的解决方案。Javascript angularJS中的多状态按钮式切换,javascript,angularjs,Javascript,Angularjs,我想在表中实现一个功能,用户可以通过点击来设置单元格的值。 可以说有3-4个状态,也可以附加一个ng模型 我在angularjs中寻找切换按钮,但它们只是开/关类型 简言之;单击按钮将设置值为:活动、非活动、排除 正在寻找具有多个状态的解决方案。 非常感谢您的帮助。没什么大不了的 当我在Angular中创建菜单时,在每个项目上,我都有一个选择功能,然后从列表中选择特定的对象 制作iterable按钮更为平滑: var i = 0; $scope.states[ { text : "Act
非常感谢您的帮助。没什么大不了的 当我在Angular中创建菜单时,在每个项目上,我都有一个选择功能,然后从列表中选择特定的对象 制作iterable按钮更为平滑:
var i = 0;
$scope.states[
{ text : "Active" },
{ text : "Inactive" },
{ text : "Excluded" }
];
$scope.currentState = $scope.states[i];
$scope.cycleState = function () {
i = (i + 1) % $scope.states.length;
$scope.currentState = $scope.states[i];
// notify services here, et cetera
}
<button ng-click="cycleState">{{currentState.text}}</button>
实际的状态数组甚至不需要是$scope的一部分,如果这是您使用这些对象的唯一位置,那么$scope上唯一需要的对象就是currentState,您可以在调用cycleState方法时设置它。检查下面的工作示例: 和控制器代码
function MyCtrl($scope) {
$scope.btnarr=0;
$scope.btnTxt=["Active","Inactive","Excluded"]
$scope.change=function(){
switch($scope.btnarr)
{
case 0:
$scope.btnarr=1;
break;
case 1:
$scope.btnarr=2
break;
case 2:
$scope.btnarr=0;
break;
}
}
}
或
控制器的较短版本
function MyCtrl($scope) {
$scope.btnarr=0;
$scope.btnTxt=["Active","Inactive","Excluded"]
$scope.change=function(){
$scope.btnarr = ($scope.btnarr + 1) % $scope.btnTxt.length;
}
}
和HTML
<div ng-controller="MyCtrl">
<button ng-modle="btnarr" ng-Click="change()">{{btnTxt[btnarr]}}</button>
</div>
这里有两种可能:从列表中选择状态或单击按钮本身循环 JS代码如下所示:
angular.module('test').directive('toggleValues',function(){
return {
restrict: 'E',
replace: true,
template: '<div>Set Status:<div ng-repeat="value in values" class="status" ng-click="changeTo($index)">{{value}}</div><span ng-click="next()">Current Status (click to cycle): {{values[selectedValue]}}</span></div>',
controller: ['$scope', '$element', function ($scope, $element) {
$scope.values = ["Active", "Inactive", "Pending"];
$scope.changeTo = function (index) {
$scope.selectedValue = (index < $scope.values.length) ? index : 0;
};
$scope.next = function () {
$scope.selectedValue = ($scope.selectedValue + 1) % $scope.values.length;
// the modulo is stolen from Norguard (http://stackoverflow.com/a/18592722/2452446) - brilliant idea
};
$scope.selectedValue = 0;
}]
};
});
HTML:
好吧。这不是什么新主意,但我接受了。另一种修改这些类型事物的干净方法是在两个语句中:i+=1;i%=长度;从微操作的角度来看,没有真正的区别。但是它看起来很干净。
<div ng-app="test">
<toggle-values></toggle-values>
</div>