Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

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>

like image 914
David Trinh Avatar asked Dec 08 '22 01:12

David Trinh


2 Answers

You could easily use ng-style here

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

Using ng-class it would be

Markup

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

CSS

.myOwnBg {
   background-color: yellow;
}
like image 106
Pankaj Parkar Avatar answered Dec 11 '22 08:12

Pankaj Parkar


Just the way you did with 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.

like image 41
hansmaad Avatar answered Dec 11 '22 10:12

hansmaad