2

How can I change color of elements using css classes with angular js. I read some stuff online but somehow I am missing something as it does not work for me.

My js fiddle:

http://jsfiddle.net/ynko3ct3/1/

Code:

<p class="change-background-color">No difference!</p>
 <form>
 <div class="form-group">
      <label>Header color</label>
      <input class="form-control" type="text"  ng-model="Headercolor" placeholder="#f00">
    </div>
    </form>

css

.change-background-color { background-color: {{Headercolor}}; }

2 Answers 2

4

Please check the updated fddle: http://jsfiddle.net/ynko3ct3/2/

You should use ng-style directive to change style attribute in HTML, not in CSS like this:

<p class="change-background-color" ng-style="{'background-color':Headercolor}">
  No difference!
</p>
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way where I don’t have to change a lot in HTML. The problem is that there are many elements like links and I don’t want to go and add ng-style everywhere
Angular v1.x can affect your HTML, templates - only if you change them accordingly. but never your CSS
1

you can check also this link : PLUNKER DEMO

need to use ng-style="yourVariableName" in your <p></p> tag and call a function on change of input field to set input field color for <p></p> tag.

In html:

<p ng-style="backColor">this is a simple background color seter</p>
<input ng-model="headerColor" ng-change="setColor()">

and in your controller:

$scope.headerColor = '#cd0a0a';
  $scope.backColor = {'background-color':$scope.headerColor};
  $scope.setColor = function() {
    $scope.backColor = {'background-color':$scope.headerColor};
  };

2 Comments

Can I use the same from a directive?
yep, you can from a directive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.