Angular and RequireJS - Part 2

Part one covered the basics of how to set up a project using Require, and in this post I’ll cover the more Angular specific details.

Round the houses

Application frameworks without the concept of Modules have very a simple Require setup, if file/pseudo class A depends on file/pseudo class B, you simply specify the dependency in the array of the define block and give it a name in the main function arguments. Application frameworks with modules require slightly more thought, and on the way to this I went through several overly complex iterations gleaned from many different blog posts until I settled on a surprisingly simple and robust solution.

In Brief

The crux of the solution rests on defining directives, controllers and services (read any provider type) in their own files and specifying them as dependencies of the containing module.

The functional units

DemoFactory.js

define([

], function (

) {
  return [
    function (){

      var demoMessage = 'Hello from DemoFactory';
      var getDemoMessage = function() {
        return demoMessage
      }

      return {
        getDemoMessage: getDemoMessage
      }
    }
  ];
});

DemoController.js

define([

], function (

) {

  return [
    '$scope', 'DemoFactory',
    function(
      $scope, DemoFactory
    ) {
      $scope.demoMessage = DemoFactory.getDemoMessage();
    }
  ];
});

DemoDirectiveTemplate.html

<div>Message: {{message}}</div>  

DemoDirective.js

define([  
  'text!demo/partials/DemoDirectiveTemplate.html'
], function (
  template
) {

  return [
    function() {
      return {
        restrict: 'A',
        scope: {
        message: '='
        },
        template: template,
        link: function(scope, element, attrs){

        }
      }
    }
  ];

});

The module definition

define([  
  'angular',
  'demo/services/DemoFactory',
  'demo/controllers/DemoController',
  'demo/directives/DemoDirective'
], function (
  angular,
  DemoFactory,
  DemoController,
  DemoDirective
) {
  var DemoModule = angular.module('demo', [])
    .factory('DemoFactory', DemoFactory)
    .controller('DemoController', DemoController)
    .directive('demoDirective', DemoDirective)
  return DemoModule;
});

Including the module in your app

define([  
  'angular',
  'demo/DemoModule'
], function (
  angular,
  DemoModule
) {
  return angular.module('app', [
    'demo'
  ])
});

Conclusions and advantages

As you can see from the main app definition, including a dependency on the module is really transparent. Simply specify it in the app file’s define block and reference it as dependency within the app module definition, and you’re away!

Source files

Check out the source files to see it in action.

Note that you’ll need to navigate to the folder in a terminal app and run npm install and bower install