castillo-io / angular-css

CSS on-demand for AngularJS [Looking for New Maintainers]
http://castillo-io.github.io/angular-css/#/
MIT License
470 stars 86 forks source link

Doesn't work if dependencies are defined on a directive. #51

Open mconner opened 8 years ago

mconner commented 8 years ago

If I want to a service or constant available as a dependency on the directive, it fails. Looking at the demo, this works:

myApp.directive('magenta', function () {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'directives/magenta/directive-magenta.html',
    css: {
      href: 'directives/magenta/directive-magenta.css',
      /* Preload: this will trigger an HTTP request on app load.
       * Once the stylesheet is added, it will be loaded from the browser cache */
      preload: true
    }
  }
});

But this does not

myApp.directive('magenta', function ($log) {
    $log.debug("in magenta directive");
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'directives/magenta/directive-magenta.html',
    css: {
      href: 'directives/magenta/directive-magenta.css',
      /* Preload: this will trigger an HTTP request on app load.
       * Once the stylesheet is added, it will be loaded from the browser cache */
      preload: true
    }
  }
});

If I'm understanding the way this works, the directive factory is executed once in angular-cs.js to find the css definition and add appropriate event handlers.
var directive = angular.copy(originalDirectiveFactory)(); And when this fails, it is silently ignored (since many directives dont have css and might be written such that they might fail).:

However, this ignores the dependencies required by the factory. It looks like as long as the factory, itself, doesn't access the dependencies, or guards for undefined, and can return an object that has at least the the css def, it should work. In my case, I had a $log.debug that failed, because the $log is undefined, but was also using a constant to defined part of the path to the css and template.

Do you think it would it be feasible to use the $injector, so that the factory can execute properly as it would in normal use?

mconner commented 8 years ago

It looks like the initial call on the factory is there primarily (solely) to determine if a directive has css, so that it can decorate the directives that require it. The css it actually uses is what is provided by the directive Provider (~ line 596 of angular-css.js), and that is coming from the directive factory function, this time injected with dependencies, and then decorated. If so, we could simply check for null arguments on the factory, and return a dummy directive definition. That seems to work, though I'm not sure how that affects preloading.

alexcastillo commented 8 years ago

Hi @mconner

Can you please submit a PR?