ps0604 ps0604 - 1 year ago 86
AngularJS Question

Angular JS directive - location of CSS file relative to HTML

My directive uses an HTML file. The HTML file uses a CSS stylesheet. I need to distribute the directive js, HTML and CSS files, so the CSS location definition needs to be relative to the HTML.

Note: This is how I solved the location of the HTML, I have pending to solve the location of the CSS file.

I put the CSS file in the same folder as the HTML file, and then defined in the HTML:

<link rel="stylesheet" href='somefile.css'>

however this points to the domain root, not to the HTML file location.

Any ideas how to achieve this?

Answer Source

I think there are two ways to fix your issue as you don't know where the directives are located:

Solution 1 - Ancient HTML Way

If the length of the CSS is small, you can directly include it in your template HTML itself, through the style tag.

<style type="text/css">
    Add style rules here

Solution 2 - The Angular Way(most recommended)

Use ngHref directive.

In your directive.js code, you can just put the path of the directive.html to a scope/rootScope variable and then you can access it from the directive.html

In directive.js

link: function (scope, iElement, iAttrs) {
     scope.htmlPath = <path of templateURL>;

In directive.html

<link rel="stylesheet" ng-href="{{ htmlPath }}/filename.css">


I hope you are not using Gulp to build the angular JS code. But, If your are using gulp, you can add a gulp task and pipe all the CSS to a single CSS and can inject to your index.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download