opensas opensas - 1 month ago 23
AngularJS Question

angular.js - best practice for defining a utility library

I'm giving my first steps with angular, and I need to define a utility helper library, with a couple of function methods, something like

dataHelper.parse
,
dataHelper.sanitize
, etc

What would be the recommended way to organize it in angular?

Answer

For utility methods, I would organize them in a library outside of the Angular framework, but with a small dependency on angular.extend. If you want your library completely independent of Angular, you can substitute extend with your own implementation.

Wrap your utility API in a JavaScript enclosure and expose your library as a property of window (in the example below, I've named my library myLibrary, but you're free to choose whichever name you like). By attaching your library as a property of window, you will be able to reference 'myLibrary' without qualification. If you are curious, this is exactly how the angular library is exposed.

 (function (window, document) {
     'use strict';

     // attach myLibrary as a property of window
     var myLibrary = window.myLibrary || (window.myLibrary = {});

     // BEGIN API
     function helloWorld() {
         alert('hello world!');
     }

     function utilityMethod1() {
         alert('Utility Method 1');
     }

     function utilityMethod2() {
         alert('Utility Method 2');
     }
     // END API

     // publish external API by extending myLibrary
     function publishExternalAPI(myLibrary) {
         angular.extend(myLibrary, {
             'helloWorld': helloWorld,
             'utilityMethod1': utilityMethod1,
             'utilityMethod2': utilityMethod2
         });
     }


     publishExternalAPI(myLibrary);

 })(window, document);

Usage

Once the script is added, you can use your library from anywhere - services, factories, providers, controllers, directives etc.

<script type='text/javascript' src='angular.js'></script>
<script type='text/javascript' src='myLibrary.js'></script>

<script>
      myLibrary.helloWorld();
      myLibrary.utilityMethod1();
      myLibrary.utilityMethod2();
</script>

Utility Library vs Angular Services

The reason that I prefer utility functions to reside in their own library rather than in angular services is because I think of them as being separate from the angular ecosystem. These utility functions are pretty much stand-alone and are module agnostic, while angular services/factories work closely with other parts of angular, including controllers and directives, and are very much closely tied to the module.

Extending Angular

If you really wanted, you could even extend the angular library itself. Just substitute myLibrary with angular in the script (Note: this may not be advisable as it would make your scripts dependent on the Angular implementation).