2

I have an angular app and need to apply some CSS styles on a page, at runtime.

Solution using ng-style is not scalable:

I am aware that for specific (known) items, this can easily be done using the ng-style directive e.g.:

<div id="mydiv" ng-style="{color: bgColor}">ABCD</div>

However, this technique cannot be applied to all the <a> or <p> tags on the page. How does one apply a dynamic style based on an angular scope variable to ALL instances of a tag on the page?

Something like the following would be ideal:

<style>
.in3_counter {color: {{settings.in3Color}};}
.in4_counter {color: {{settings.in4Color}};}
</style>

Update: The value of the css scope variables isn't predetermined, so I we don't know what colors would be applied to the elements as the variables are set at runtime (e.g. with color picker).

Any suggestions?

1 Answer 1

3

Check the following example:

var COLOR_CTRL = function($scope, $sce) {

  $scope.changeColor = function(color) {
    $scope.style = $sce.trustAsHtml('a, p {color: ' + color + '}');
  };

  $scope.changeColor('#000');

};

var app = angular.module('app', []);

app.controller('ColorCtrl', ['$scope', '$sce', COLOR_CTRL]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<div ng-controller="ColorCtrl" ng-app="app">

  <a href="#">anchor</a>

  <p>paragraph</p>

  <div>

    <button ng-click="changeColor('#f00')">red</button>
    <button ng-click="changeColor('#0f0')">green</button>
    <button ng-click="changeColor('#00f')">blue</button>

  </div>

  <style data-ng-bind-html="style"></style>

</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - however, I wouldn't know what colors would be applied to the elements as the variables are set at runtime (e.g. with color picker). So there is no prior knowledge of the values of the variables. I'll update my post with this info.
@mozami Check the updated suggestion after your update.
Thanks - This looks good. I'll give it a try and post back / accept the answer.

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.