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
Change button color after click in Angularjs
提问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.start
function so that once the button is clicked, the color of the button turns yellow.
我可以在$scope.start
函数中填写什么,以便单击按钮后,按钮的颜色变为黄色。
回答by Ronnie
you can use ng-class
Define 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-danger
from 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 buttonStyle
and buttonText
in your scope
buttonStyle
并buttonText
在您的范围内定义
$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