Html 单击 Angularjs 后更改按钮颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19779635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:03:56  来源:igfitidea点击:

Change button color after click in Angularjs

javascripthtmlangularjs

提问by puscan

This is what I have now: index.html

这就是我现在所拥有的:index.html

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
    <button class="btn btn-danger" ng-click="start()">Start</button>
  </div>
</div>


function TodoCtrl($scope) {
  $scope.start = function() {

  };
}

What can I fill in the $scope.startfunction so that once the button is clicked, the color of the button turns yellow.

我可以在$scope.start函数中填写什么,以便单击按钮后,按钮的颜色变为黄色。

回答by Ronnie

you can use ng-classDefine a var like $scope.started = false;and inside you start function set it to true. On your button do this:

您可以使用ng-class定义一个类似的 var$scope.started = false;并在您的启动函数中将其设置为 true。在您的按钮上执行以下操作:

ng-class="{'btn-warning': started, 'btn-danger': !started}"

ng-class="{'btn-warning': started, 'btn-danger': !started}"

another way to write it:

另一种写法:

ng-class="started && 'btn-warning' || !started && 'btn-danger'"

ng-class="started && 'btn-warning' || !started && 'btn-danger'"

note: remove btn-dangerfrom your curre class attribute

注意:btn-danger从您的当前类属性中删除

EDIT

编辑

The newer, more common way is the standard ternary operator (also easier to read):

更新、更常见的方法是标准的三元运算符(也更容易阅读):

ng-class="started ? 'btn-warning' : 'btn-danger'"

ng-class="started ? 'btn-warning' : 'btn-danger'"

回答by El Dude

The probably best way is to bind the button style to the variable like this:

可能最好的方法是将按钮样式绑定到变量,如下所示:

<button class="button button-block {{buttonStyle}}" ng-click="start()">
    {{buttonText}}
</button>

and define buttonStyleand buttonTextin your scope

buttonStylebuttonText在您的范围内定义

$scope.buttonText = "Start";
$scope.buttonStyle="button-calm";

$scope.start = function(){
    $scope.buttonText = "Clicked!";
    $scope.buttonStyle="button-assertive";
}

回答by Kamal Pandey

This can be done using directive easily. You can have a look at this. https://www.youtube.com/watch?v=sYexGR7FQX0

这可以使用指令轻松完成。你可以看看这个。 https://www.youtube.com/watch?v=sYexGR7FQX0