Javascript 如何使用 ng-class 更改背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32346539/
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-23 07:55:27  来源:igfitidea点击:

How can I change the background-color using ng-class?

javascriptcssangularjsangularjs-ng-repeatng-class

提问by David Trinh

I am trying to change the background color whenever someone inputs a '5' while using ng-class. I am really new to AngularJS and just writing things to get the hang of it. Am I supposed to use an ng-if somewhere or have to change my CSS? Also where would I have to input the code? I know it has to be somewhere where I filter the number but am totally lost on how to write the code. Please help!

每当有人在使用 ng-class 时输入“5”时,我都会尝试更改背景颜色。我对 AngularJS 真的很陌生,只是写一些东西来掌握它。我应该在某处使用 ng-if 还是必须更改我的 CSS?另外我必须在哪里输入代码?我知道它必须在我过滤数字的地方,但完全不知道如何编写代码。请帮忙!

Here is my code:

这是我的代码:

<body ng-init="numbers=[0,1,2,3,4,5]">
<nav>
  <a href="#" ng-click="tab='numbers'" ng-class="{active:tab=='numbers'}">Numbers</a>
  <a href="#" ng-click="tab='form'" ng-class="{active:tab=='form'}">Form</a>
</nav>
<div ng-switch="tab">
  <div ng-switch-when="numbers">
    <input type="text" ng-model="myValue" />
    <h1 ng-repeat="number in numbers | filter:myValue"}>{{ number }}</h1>
  </div>
  <div ng-switch-when="form">
    <button ng-click="numbers.pop(); tab='numbers'">Pop</button>
    <button ng-click="numbers.push(numbers.length); tab='numbers'">Push</button>
  </div>
</div>

回答by Pankaj Parkar

You could easily use ng-stylehere

您可以ng-style在这里轻松使用

<input type="text" 
 ng-model="myValue" 
 ng-style="{'background-color':myValue == 5 ?  'red': 'white'}"/>

Using ng-classit would be

使用ng-class它会

Markup

标记

<input type="text" ng-model="myValue" ng-class="{'myOwnBg': myValue == 5}"/>

CSS

CSS

.myOwnBg {
   background-color: yellow;
}

回答by hansmaad

Just the way you did with ng-class="{active:tab=='numbers'}"

就像你做的那样 ng-class="{active:tab=='numbers'}"

<input type="text" ng-model="myValue" ng-class="{ bg : myValue == 5 }">

If you don't want to define a css class, you could use ngStyle.

如果您不想定义 css 类,则可以使用ngStyle.