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

时间:2015-09-02 07:02:05

标签: javascript css angularjs angularjs-ng-repeat ng-class

每当有人输入“' 5”时,我都会尝试更改背景颜色。使用ng-class时。我是AngularJS的新手,只是写东西来掌握它。我应该使用ng-if某个地方还是必须改变我的CSS?我还要在哪里输入代码?我知道它必须是我过滤数字的地方,但我完全迷失了如何编写代码。请帮忙!

这是我的代码:

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

2 个答案:

答案 0 :(得分:10)

您可以在此处轻松使用ng-style

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

使用ng-class它将是

<强>标记

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

<强> CSS

.myOwnBg {
   background-color: yellow;
}

答案 1 :(得分:2)

就像你使用ng-class="{active:tab=='numbers'}"

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

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