0

I am building an application which sends 1-5 views and the appropriate model&controller to the client on page load. The user is guided to each view consecutively using routing and this is working just fine.

The problem I have is that I want to apply style rules to the view, but the style rules are tied to the model. I know that I cannot simply save some css as text and inject them into a <style></style> block. I cannot simply add a reference to a .css file because all of this is coming from a database, and each model could potentially have style rules that conflict with another model.

Any advice on how to solve this issue?

1
  • See ng-class and you're able to bind it to an object of style class name properties to booleans indicating their applied state. Commented May 22, 2014 at 0:34

2 Answers 2

1

You can insert a style element into the page:

angular.module('myApp', [])
.controller('MyController', function($scope) {
  $scope.css = ".red { color: red;}"
})
.directive('myDirective', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      var style = angular.element('<style type="text/css"></style>');
      style.append(scope.css);
      elem.append(style);
    }
  }
});

Plunker Demo

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

3 Comments

is there a way to get this to work in IE8? I've tried throwing all the IE8 best practices at this problem and it is still not working.
Here, it will work in IE (but won't in other browsers): plnkr.co/edit/C37kCWFAfE8VAvUt0bQF?p=preview I'll leave the real work of making it work in both places to you ;-)
..meaning you should be able to combine the two solutions
1

Here's an example of using ng-class. If you can get your css rules out of the database and into a $scope object like this:

$scope.css = {
    divcss:{
      'border-style': 'solid',
      'border-width': '2px',
      'background-color': 'yellow'
    },
    headercss:{
      'font-weight': 'bold',
      'font-size': '50px'
    }
  }

Then you can apply them to your view element like this:

<div ng-style="css.divcss">Check it out</div>
<span ng-style="css.headercss">Big ol' Header</span>

Plunker demo

1 Comment

Thanks Jerrad. This probably wouldn't work for what we are trying to do since the css code has to be formatted in json, which I should have mentioned in the question.

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.