How to manipulate styles of directive in AngularJS?


I'm writing a component using AngularJS and AngularJS directives.

I'm doing something like this:

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

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }

I want to be able to change style of my component (using CSS), something like this:

<my-tag class="MyClass"></my-tag>

Besides this I want to be able to manipulate all elements style inside my component (HTML markup inside of my-tag).

Do you have any advice or useful examples how to manipulate the style properties of custom tags using AngularJS?


app.directive('bookslist', function() {

    return {
    	scope: true,
        templateUrl: 'templates/bookslist.html',
        restrict: "E",
        controller: function($scope){

        link: function(scope, element, attributes){


.customClass table{
	background: tan;

.customClass td{
	border: 1px solid #ddd;

<!DOCTYPE html>

    <link href="app.css" rel="stylesheet">
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>

<body ng-app="app">
    <div ng-controller="myCtrl">



I didn't found the perfect solution just yet, but I'm following John Papa's styling of controllers even with directives:

  • the directive is a folder (directiveName.directive)
  • 3 files inside: directiveName.directive.js, directiveName.template.html, directiveName.styles.css
  • use templateUrl when declaring the directive. The template has the link to the css file, as usual

I found it to be very clean and follows a pattern. The bad side of it is that you create several <link> tags near the directives in the rendered HTML (not seem to be a issue still, though). Check out this comment too.

That being said, take a look at Angular 1.5 component's. It's relatively new and has a much better approach. Now I use directives only for DOM manipulation (not reusability as components).

Here is an example, please note that this is probably not the best use of AngularJS, being declarative, you would likely want to just put the classes on the markup. However, just so you understand what's going on, let me demonstrate a simple directive to do what you first asked.

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

MyApp.directive('myTag', function($compile) {
    return {
        restrict: 'E', // this means it will be an element
        link: function(scope, element, attrs, ctrl) {
            // First, I included the $compile service because it will be needed
            // to compile any markup you want to return to the element.

            // 1. Add the class, as you wanted

            // 2. Add markup
            var html = '<div>Hello World</div>';
            //Compile it and add it back

Finally, on your markup, you just put this in:

<my-tag />

This video can help you solving your question :)
By: admin