Isolate the CSS formatting from the template within an AngularJS directive

Here is an angular directive I created for a template. I wanted to keep the css styling separate from the template so that when I use the custom tag in my html file like <my-box></my-box> or <my-box></my-box>, I can configure the css styling for each tag from a separate file using classes like

<my-box class=customStyle1></my-box>
and
<my-box class=customStyle2></my-box>
. These styles are defined in a separate Json file, like this:

{
 "myStyle":{
     "background-color":"#AAB000",
      "height":"100px",
       -----
       -----
   }
}

You can view an example of my template here.

Code snippet

 counterbox.directive('myBox', function ($http) {

        return {
            restrict: 'EAC',
            template: '<div id=l1 style="height:100px"><table style="width:100%;height:100%;text-align:center;border-style:solid black;border-collapse:separate;border-spacing:2px" align="center"><colgroup><col style="width:33%"/><col style="width:33%;text-align:center"/><col style="width:33%"/></colgroup><tr style="color:black;font-family:sans-serif;font-size: 1em;font-weight:normal;padding-bottom:-5px;"><th style="text-align:center">X</th><th style="text-align:center">Y</th><th style="text-align:center">Z</th></tr><tr style=""><td style="background-color:lightblue;color:black">{{w.l}}</td><td style="background-color:orange;color:black">{{w.m}}</td><td style="background-color:red;color:black">{{w.h}}</td></tr><tr style="background-color:#BCC633;color:white;font-size:2em"><td id=g1 height="50%" colspan="3">{{w.s}}</td></tr></table></div>',

            replace: true,
            scope: {
                w:'='
            },
            link: function (scope, element, attrs) {                    
                scope.s = +scope.l + +scope.m + +scope.h;

            }
        };
    });

## Instead of using templateUrl, I separated common styling through an external css file. However, there were two issues: 1. The css file was not accessible for configuration by users or clients, who could only configure the Json file. 2. If you look at my table, each row has a unique color which needs to be modified using the css configurations provided through the Json.

Answer №1

  1. Make sure to keep your CSS in a separate file (preferably with a .css extension)
  2. Utilize the "templateUrl" attribute rather than "template" when working with directives in AngularJS. More information can be found in the AngularJS Templates
  3. Don't forget to link your CSS file in your HTML template using the
    <link type="text/css" rel="stylesheet" href="style.css"/>
    tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An effective method for adding a character to a number within an input field with the use of AngularJS

There is an input field in my code of type text that is connected to a variable within a certain scope. <input type=text= ng-model="vm.someProperty"> I am looking to have the input display the value with a percentage sign after it, without changing ...

JavaScript element styling in a Partial view, experiencing issues with functionality

In the main view, the javascript element is working fine. However, in the partial view it seems to not be functioning even though it is correctly formatted. Any ideas on how to fix this issue? Check out this fiddle for reference: http://jsfiddle.net/bgrin ...

Display a dynamic HTML table in PHP using print statements

Looking for assistance... I have a form set up with a dynamic table integrated. Does anyone know how to pass this through php and then print it out on a php page in order to save the page as a pdf? This part has me stuck. I've searched high and low ...

Is it advisable to include the `engine` attribute in the packages.json file for a web browser library project?

When creating a JS library project meant for browser use, do I need to include the engines field in the packages.json file? ...

The Popover in Twitter Bootstrap disappears beneath the navigation bar

I have a help button located in my navigation bar that triggers a popover feature. <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <div class="nav pull-right"> ...

Different ways to generate DOM element using jQuery

When it comes to creating a new DOM element from JavaScript or jQuery code, there are numerous methods to consider. Some examples include: $('<div>').prop('id','someid').addClass('someclass'); $('<div& ...

jsx eliminate parent based on dimensions

Imagine I have a DOM structured like this <div className="parent"> <div>child 1</div> <div>child 2</div> </div> If the view is on mobile, I would like the DOM to transform into <div>child 1</ ...

What is the best way to create a div that horizontally scrolls and contains multiple other div elements?

I've set up a div that contains other divs, including images and text. My goal is to make the main div scrollable horizontally while aligning the inner divs using inline-block. However, when I apply: overflow-x: scroll; The main div ends up with tw ...

Creating a CSS rule that specifically targets a particular div id on a webpage can be accomplished by using the selector syntax to select

Is there a way to conditionally apply a @media print css ruleset only when a specific div is present on the page? For example, I have the following css to assist in printing #mytargetdiv: @media print { .inside-article > :not(#mytargetdiv), .inside ...

Exporting stylesheets in React allows developers to separate

I am trying to figure out how to create an external stylesheet using MaterialUI's 'makeStyles' and 'createStyles', similar to what can be done in React Native. I'm not sure where to start with this. export const useStyles = m ...

timings and pauses utilizing JavaScript

Currently, I am facing a challenge while working on a Simon Says game. My struggle lies in the part where I need to illuminate the buttons that the user has to click. I am using a "for" loop to iterate through each element in the array where I have stored ...

Strategies for avoiding the opening of a new tab when clicking on a link in ReactJs

RenderByTenantFunc({ wp: () => ( <Tooltip id="tooltip-fab" title="Home"> <Button className="home-button"> <a href={ ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

The module 'angular' could not be located and is causing an error

Currently, I am in the process of transitioning from Angular 1 to Angular 2 following this guide: . However, when I try to run the application using npm start, it displays an error saying 'Cannot find module 'angular''. This is a snipp ...

Function asynchronously returning Promise even after Await statement is executed

I've been attempting to develop a function that retrieves data from a document in the Firebase database using Nodejs: module.exports = async (collectionName, documentId, res) => { const collection = db.doc(`/${collectionName}/${documentId}`); t ...

hiding the UI filter with AngularJS: a step-by-step guide

$scope.tableOptions = { "aLengthMenu": [[10, 50, 100, -1], [10, 50, 100, 'All']], "searching": false, "paging": true, "info": false, "lengthChange": false }; Visit this link for more information: ...

Is the init-models.js file generated by sequelize-auto being used in my application to establish associations?

I am currently developing an express rest api using sequelize. After generating my models with the help of sequelize-auto (which created init-models.js), I have encountered an issue with utilizing associations in my tables. Although the associations are de ...

The onchange tag fails to trigger my Javascript function when selected

Here is the code I have: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID ...

A guide on leveraging the each() method for looping through a JSON document

I am hoping to display elements sourced from a JSON file. Here is the JSON data "2015": { "img": "<img src = \"../images/images/images_of_members/image1.jpg\">", "img2": "<img src = \"../images/images/images_of_members/image2.jpg& ...

What is causing the navigation bar on stackoverflow.com to move suddenly when clicked?

Just noticed the sleek new navigation bar on stackoverflow. Reminds me of the bootstrap design I've been using. However, I've encountered a similar issue on my website where the navigation bar jumps slightly when clicked. Does anyone have any su ...