Search code examples
javascriptcssangularjsangularjs-ng-repeatng-class

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>


Solution

  • 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;
    }