9

I have an AngularAMD app, and I have a directive that depends (in a RequireJS sense) on that app (it is the Angular module in which that directive "lives").

If I use routing, and use the directive inside a routed view, then there is a route that includes a controllerUrl, which depends on the file containing the directive.

If I don't, then...

Well, it's enragingly circular. If I tell the app that it depends on the directive, I get a circular dependency. If I don't, Angular doesn't know about the directive and the tag is just ignored.

Short of reproducing the entire controller-resolving mechanism from AngularAMD, is there a way I supposed to do this?

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • Why should the directive depend on app? I didn't use RequireJS, but it seems wrong. Maybe it is app should depend on the directive? So if you load an app, the directive is loaded with it. Also it would be easier to understand the problem if you post some code example which reproduces the issue. – Borys Serebrov Jan 28 '16 at 23:15
  • Directives have to be in a module -- the app is that module. – Michael Lorton Jan 29 '16 at 05:42

1 Answers1

3

I think that there can be two cases:

1) Your directive is standalone and doesn't actually depend on anything in the application.

In this case you can put it into own module (both in terms of RequireJS and angular):

// my-directive.js
var module = angular.module('my-directive', []);

module.directive('myDirective', [
  ...
]);

// app.js (depends on my-directive.js)
var app = angular.module('myapp', ['my-directive']);

This use case is supported by AngularAMD, see 3rd Party AngularJS Modules.

2) Your directive depends on something inside your app. In this case - put it into the same module (also both in terms of angular and RequireJS).

// app.js
var app = angular.module('myapp', []);

app.directive('myDirective', [
  ...
]);

3) [Update] One more solution: AngularAMD also supports a special case to define and load an application wide module.

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
  • In either case, I would need to load all the code for the directive when I loaded the app, which would defeat the point of using Require. – Michael Lorton Jan 29 '16 at 16:11
  • @Malvolio do you mean that in those 2 cases both app.js and directive.js will be loaded from the start? And you want it like "load only app.js and load directive.js only when necessary"? – Borys Serebrov Jan 31 '16 at 22:14
  • @Malvolio actually AngularAMD supports loading 3rd party modules, see [this](https://github.com/marcoslin/angularAMD#3rd-party-angularjs-modules), so if you put your directive into separate module (approach 1), it should work. Also there is a special use case in the [documentation](https://github.com/marcoslin/angularAMD#loading-application-wide-module) which looks like exactly what you want. – Borys Serebrov Jan 31 '16 at 22:46