Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Created June 23, 2014 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwhinnery/60464b67b11fc9a9fad1 to your computer and use it in GitHub Desktop.
Save kwhinnery/60464b67b11fc9a9fad1 to your computer and use it in GitHub Desktop.
A basic structure for a CommonJS (node/browserify) AngularJS controller
// Require any dependencies in the node.js style (thanks Browserify!)
var buzz = require('node-buzz');
/*
The arguments to an Angular controller constructor are framework
APIs that are provided to your controller at runtime. This
is a technique for "dependency injection" in JavaScript. Note that
these argument names are significant! You can't change them without
making other configuration changes.
*/
var MessageController = function($scope, $http) {
// Step one in an Angular controller is usually initializing instance
// variables for UI state
$scope.messageVisible = true;
// Next, you'll likely define functions on the scope object that can
// be called from the view layer when interaction events happen, like
// mouse clicks
$scope.doSomething = function() {
// inside an event handler, you'll probably update your controller's
// state by modifying the $scope object
$scope.messageVisible = false;
};
// Now, you may need to execute some logic when a new controller of
// this type is created. Hit a web service? Create a sound object?
// Do whatever init stuff you need to do now.
};
/*
Okay, WTF is this? Remember how I said that the constructor's
argument names are important? Angular looks for those argument
names in your script when it loads, and injects the needed
services at that time. For it to do that, you need to name
your constructor arguments a certain way. But what if your
script is minified? The arguments will be renamed! If that's
the case, you need to explicitly tell Angular which services
it should provide to your controller, like so:
*/
MessageController.$inject = ['$scope', '$http'];
// Export the public module interface, the controller constructor
module.exports = MessageController;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment