SrinivasAppQube SrinivasAppQube - 7 months ago 21
HTML Question

How to change the button color using ng-click function?

I got the buttons list from resource. It consist of 10 buttons like
t1,t2,t3,t4,t5,t6,t7,t8,t9,t10

When I click the on t1 button first time button color change to red. Second time I click on same button color change to green.

Please tell me how to do this

<div class="col-sm-2 col-lg-1 col-md-1" ng-repeat="table in tables" style="margin-left:1px">
<button type="button" class="btn btn-success" ng-click="getTable(table)">{{table.tablename}}</button>
</div>


this is my method

$scope.ng-click=gettable(table){
//
}

Answer

It's easy. Just bind one more property with your all the items in tables array like this-

for(var i = 0; i < $scope.tables.length; i++)
{
    $scope.tables[i].btnClass = "btn-success";
}

then in HTML, assign this class like this:

<button type="button" class="btn {{table.btnClass}}" ng-click="getTable(table)">
{{table.tablename}}</button>

and ng-click function as:

$scope.getTable = function(table) {
    table.btnClass = table.btnClass == "btn-info" ? "btn-success" : "btn-info"
}

Or if you want to change manual colors then create one class in css like this:

.red-button {
    background-color: "red";
}

Then in the function

$scope.getTable = function(table) {
    table.btnClass = table.btnClass == "red-button" ? "btn-success" : "red-button"
}