Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi State button like toggle in angularJS

I want to implement a feature in table where user can set value of cell by clicking on it. there can be say 3-4 states,also a ng-model attached to it.

I looked for the toggle button in angularjs but they are mere on/off type.

In short; Clicking on the button will set the value as: Active, Inactive, Excluded Looking for solution with multiple state. Any help with this is really appreciated.

like image 973
Sushrut Avatar asked Dec 11 '22 11:12

Sushrut


2 Answers

Check the below working example :

http://jsfiddle.net/vishalvasani/ZavXw/9/

and controller code

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;                
        }
    }
}

OR

Shorter Version of Controller

function MyCtrl($scope) {

    $scope.btnarr=0;
    $scope.btnTxt=["Active","Inactive","Excluded"]
    $scope.change=function(){
      $scope.btnarr = ($scope.btnarr + 1) % $scope.btnTxt.length;
    }
}

and HTML

<div ng-controller="MyCtrl">
    <button ng-modle="btnarr" ng-Click="change()">{{btnTxt[btnarr]}}</button>
</div>
like image 141
JQuery Guru Avatar answered Dec 30 '22 17:12

JQuery Guru


There isn't much to it.

When I make menus in Angular, on each item, I'll have a "select" function, which then selects that particular object, out of the list...

Making an iterable button is even smoother:

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>

The actual array of states wouldn't even need to be a part of the $scope here, if this was the only place you were using those objects -- the only object you'd need to have on the $scope would then be currentState, which you set when you call the cycleState method.

like image 23
Norguard Avatar answered Dec 30 '22 18:12

Norguard