简体   繁体   中英

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?

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
</style>

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">

Note:

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.

您需要为css和html(模板文件)创建单独的目录,并使用从root到css文件夹的完整路径

<link rel="stylesheet" href='/angualr/css/style.css'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM