Angular JS how to read css file names that are uploaded to html page

We create a new widget in which we implement a function that reports how many css files are included in the html page.

We need the number of css files used on the page, as well as the names of the css files.

I'm a little new to angular, and I heard that this can be done using directives, but I don't know how to achieve it.

You need help. Thanks in advance.

+4
source share
3 answers

Is your application already in Angular? This jQuery code would easily accomplish this task:

var cssList = []
$('head link[type="text/css"]').each(function(){
    cssList.push($(this).attr("href"));
});
console.log("List of files:" + cssList.join());
console.log("Number of files:" + cssList.length);
+2
source

Using angular:

  .directive('cssCounter', ['$document', function($document) {

    function cssFilter(l) {
      return l.type === 'text/css' || l.rel === 'stylesheet';
    }

    function link(scope, element, attrs) {

      var links = $document[0].querySelectorAll('link');
      var linksAsArray = Array.prototype.slice.call(links, 0);
      var cssLinks = linksAsArray.filter(cssFilter);
      var cssNames = cssLinks.map(function(c) {
        return c.href;
      });


      scope.cssFiles = cssNames;
    }

    return {
      link: link,
      template: '<p>CSS count: {{cssFiles.length}}<ul><li ng-repeat="c in cssFiles">{{c}}</li></ul></p>'
    };
  }]);

plunker : http://plnkr.co/edit/TqNAOKw4biyA7akdHfa4

+1

Using external libraries, you can do this:

var links = document.querySelectorAll('link');
var linksAsArray = Array.prototype.slice.call(links, 0);
var cssLinks = linksAsArray.filter(function(l){return l.type === 'text/css';});
var cssNames = cssLinks.map(function(c){return c.href;});
var count = cssNames.length;
console.log("css count and names:", count, cssNames);
0
source

Source: https://habr.com/ru/post/1615738/


All Articles