Search code examples
angularjsangularjs-directiveangularjs-module

AnguarJS module to wrap javascript libraries


I'd like to use a library in my angular project that provides sliders written in javascript/jQuery. Therefore I would write a directive inside my project, with a certain interface to use the library-functionality. I would load the library source file in my index html. That would make the library globally available.

I would use this library in my other angular projects as well, so I'd like to create an Angular-Module (own project) with the directive so I can inject it in every project as module-dependency. Unfortunately I have no idea where to load the library and how the structure of this Angular-Module should be. Do I have to load the library inside the directives template?

template.html:

<script src="libraries/jquery-slider.js></script>
<my-slider></my-slider>

Or do I have to load/inject the jQuery-library in a different way, to get access to its functionality?


Solution

  • Well, let's assume you have a primary module. Then your index.html structure would look like the following:

    <script src="js/main.js></script>
    

    Then you add another module which is an interface / bindings provider for your library:

    <script src="js/library-binding.js></script>
    <script src="js/main.js></script>
    

    And here the question comes that you need to include the library itself somewhere. There are two major options here which are:

    Lazy loading, or the method when you want to load the library right at the moment it's gonna be used. You would need to do this inside of your directive implementation and can cause some troubles, because you will be forced to delay the element rendering until the library is loaded. Additionally, you will have another problem in case you have more than one element on the page: you will load the library more than once and this can be the source of conflicts and you would somehow need to care about it, e.g. set some global variable that library is loaded and you don't need to load it anymore (plus it should be injected in the <head> section in this case).

    Load the library always together with interface module, which is way more clear and simple; however it will always be loaded regardless of whether it is used or not.

    My personal preference is the second way, but you should really look what is best for your particular project.

    So, in this case index.html structure should look like

    <script src="js/library.js></script>
    <script src="js/library-binding.js></script>
    <script src="js/main.js></script>
    

    or, what could be better

    <script src="js/library-and-library-binding.js></script>
    <script src="js/main.js></script>
    

    In this case all dependencies are self-contained within the module file.