Writing Browserify modules for your Angular app

How to create little re-usable modules

Following up on my previous Let’s Build an angular app with Browserify post I got a few questions on how to create modules for your app. Let me show you.

Dependency injection

But what if we want to use a dependency. Simply require it and inject it:

exports.inject = function(app) {
  require('./../services/SomeService').inject(app); // Require the someservice module
  app.controller('AboutCtrl', exports.controller);
  return exports.controller;

// Pass the SomeService as parameter
exports.controller = function AboutCtrl($scope, SomeService) {
  // And profit.
  $scope.regularAngular = SomeService.getYourStuff();

This is how that SomeService would look like. Not much different, but instead of exposing a controller, we return a factory:

exports.inject = function(app) {
  app.factory('SomeService', exports.factory);
  return exports.factory;

// Any extra dependencies can just be passed in
exports.factory = function($http, $cookieStore, $resource) {

  var monkey = 'Strawberry';

  return {
    getYourStuff: function() {
      return monkey;

And that’s how we can write little re-usable modules to use in our Angular App!

I hope the above helps, and if you have any questions feel free to ask.

Happy coding.

Questions or comments?

As always, if you have any questions or comments, you can find me on Twitter.

Subscribe to the mailing list

Subscribe to the newsletter, and be the first to know when there's new post 🔥