如何使用 ng-click 功能更改按钮颜色?

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

我从资源中获得了按钮列表。它由 10 个按钮组成,例如 t1,t2,t3,t4,t5,t6,t7,t8,t9,t10

当我第一次点击 t1 按钮时,按钮颜色变为红色。第二次我点击相同的按钮颜色变为绿色。

请告诉我怎么做

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

这是我的方法

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

这是我的建议:在你的 $scope.ng-click=gettable(table){ ...... }

里面
  • 创建颜色数组
  • 每次单击按钮时,在该数组中拉取一个随机颜色值

很简单。只需将一个 属性 与表数组中的所有项目绑定,就像这样-

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

然后在 HTML 中,像这样分配这个 class:

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

和 ng-click 功能为:

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

或者,如果您想更改手动颜色,则在 css 中创建一个 class,如下所示:

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

然后在函数中

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

使用 controllerAs 语法(我建议您使用),您可以使用以下内容。

html:

<div ng-repeat="table in ctrl.tables">
    <button type="button" ng-click="ctrl.getTable(table)" ng-style="{ 'background-color': table.color }">{{table.tablename}}</button>
</div>

js:

this.getTable = function(table) {
    table.color = "red";
};

https://plnkr.co/edit/axzyUQJowlSEClszrIQs

var colors=['red','green','yellow','black','blue'];
$scope.color=null;
$scope.ng-click=gettable(table){ 
var colorToApply=colors[Math.floor(Math.random()*colors.length)];
$scope.color=colorToApply
 }

现在您可以在此处定义 css 规则

.green{
  color:green;
}
.blue{
  color:blue;
}
.red{
  color:red;
}
.yellow{
  color:yellow;
}

然后在您的视图中,您可以在要更改颜色的按钮上设置 ng-style 并将其绑定到范围内的颜色,例如

<button ng-style="color">Change color</button>