Apr 16, 2013


The normal way to to creating anguarjs component is like the following.

var sugar = angular.module('sugar', []);
sugar.controller('controller1', function($scope) {
  $scope.m1 = m1;
  $scope.m2 = m2;
sugar.constant("constant1", object);
sugar.directive("directive1", directiveFactory);
sugar.factory("factory1", providerFunction);

sugar.filter("filter1", filterFactory);
sugar.service("service1", constructor);
sugar.value("value1", object);

I have created a script to simplify the process, so that you can write code like the following.

//angular.m("sugar", [dep1, dep2], definition);
angular.m("sugar", {
  controller: {
    test: function ($scope) {
        m1: m1,
        m2: m2
  constant: {
    constant1: object
  directive: {
       directive1: directiveFactory
  factory: {
     factory1: providerFunction

//you can split the definition in to multiple piece
angular.m("sugar", definition1)
angular.m("sugar", definition2);

The good things about it are:

  1. It is not easy to create global variable
  2. The code is more readable
  3. You can create all module components in a single call, this is useful for simple application.

You can get the code at https://github.com/fredyang/angularjs-sugar. And there is an example at Plunker.