Search code examples
angularjsangularjs-material

Angular way of toggle md-button inside ng-repeat


I have some 10 buttons inside ng-repeat which basically operate like a switch to get multiple data, each of the button must pass a value to controller and in controller push that value to an array on first click and delete that value in next(toggle action).

My html code segment

<md-button id="{{choice.id}}btn{{ambutton}}" ng-repeat="ambutton in ambuttons" ng-click="getTime(choice,ambutton);" class="md-fab  md-primary" ng-class="{'active md-warn': variable,'disable md-primary': !variable}">{{ambutton}}</md-button>

Controller function

 $scope.ambutton=[1,2,3,4,5,6,7,8,9,10]
    $scope.getTime = function (choice,ambutton) {
            $scope.variable = !$scope.variable;
            if($scope.variable){
                //save the value to an array;
            }
            else{
              //remove the value from array
             }
        };

Problem facing is when i click a button all the button becomes active, i tried adding differnt variables for each button like variable0,variable1,variable2... (by adding variable{{ambutton}}) and in controller using if-elseif it's working fine, But i need a better solution can anything possible with id related to each button?


Solution

  • check this out http://jsfiddle.net/n2p1ocqz/7/

    you can use variables as an array and with index manipulate, whether choose or not, like

       $scope.ambuttons=[1,2,3,4,5,6,7,8,9,10]
       $scope.variables=[];
        $scope.getTime = function (choice, ambutton, index) {
                $scope.variables[index] = !$scope.variables[index];
                if($scope.variable[index]){
                    //save the value to an array;
                }
                else{
                  //remove the value from array
                 }
            };
    

    and your partial like

    <md-button  ng-repeat="ambutton in ambuttons track by $index" ng-click="getTime(choice, ambutton, $index);" class="md-fab  md-primary" ng-class="{'active md-warn': variable,'disable md-primary': !variables[$index]}">{{ambutton}}</md-button>