Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some thoughts on angular files. The idea here is to make the constructors for controllers, services, etc, look like normal JS constructors.
(function(module) {
// Define a controller constructor
// This looks like a plain JavaScript function
function HomeCtrl(service, $location) {
this.service = service;
this.$location = $location;
this.initialize();
}
HomeCtrl.prototype.initialize = function() {
this.service.fetch()
.success(this.fetched.bind(this));
};
HomeCtrl.prototype.fetched = function(data) {
this.data = data;
};
// Explicitly set dependencies
HomeCtrl.$inject = ['service', '$location'];
// Module comes in from IIFE
module.controller('HomeCtrl', HomeCtrl);
})(angular.module('app'));
(function(module) {
// Define a service constructor
// This looks like a plain JavaScript function
function Service($http) {
this.$http = $http;
}
Service.prototype.fetch = function(data) {
return this.$http.get('/api/url');
};
// Explicitly set dependencies
Service.$inject = ['$http'];
// Module comes in from IIFE
module.service('service', Service);
})(angular.module('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment