Sunday, September 22, 2013

Creating re-usable libraries for your project with Angularjs

There are several ways to structure your code in AngularJS and there is no right or wrong. When you start working with AngularJS I assume that you start by checking out the Angular Seed Project or using Yeoman. However at some point you will want to create libraries or widgets that you want to store in one place for re-use in other projects. For example the "lib" directory.

Examples could include:
  • Global error handler (lib/xx/xx-global-error-handler.js)
  • Authorization (lib/xx/xx-authorization.js)
  • File Upload (lib/xx/xx-file-upload.js)
You can then include these files in to your index.html like this:
<script src="lib/angular.js"></script>
<script src="lib/xx/xx-global-error-handler.js"></script>
<script src="lib/xx/xx-authorization.js"></script>
<script src="lib/xx/xx-file-upload.js"></script>
It is considered as good practice to use a two letter or more letter prefix. For example the starting letters of your surname and name or the first and last letter of your company name. In my case displayed as "xx". This helps to prevent clashes with other files and variables or names you use in your project. I also add the prefix to the name of my controllers, directives and variables.

 * @ngdoc overview
 * @name xx-my-module-name
 * @description
 * Your module description goes here
(function() {
  'use strict';
  angular.module('xx-module-name', [])
    .config(['$http',function($http) {
    .controller('XXMyCtrl', ['$http',function($http) {
    .directive('xx-my-directive', ['$http', function($http) {
Once your module is finished and you added it to the index.html file you'll also have to link it to your main app.js.
angular.module('myApp', ['xx-module-name'])
  // Define routing
  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/login', {templateUrl: 'partials/login.html'});
    $routeProvider.when('/user', {templateUrl: 'partials/user.html', controller: UserCtrl});
    $routeProvider.when('/vendor', {templateUrl: 'partials/vendor.html', controller: VendorCtrl});
    $routeProvider.otherwise({redirectTo: '/login'});
Like this you can start to plugin your own library sets as required.

General Tips on structuring your code

Personally I have started to also put normal code in to a similar fashion. If I for example need code to handle a Vendor then I'll put everything such as controllers, directives, filters and so on that are related to the vendor in to a file called vendor.js. First of all it is very easy to find what you are looking for and you don't fill up a file with several different controllers or directives in which you have to search for the right controller or directive again.

No comments:

Post a Comment