Services & Factories
Factory and service singletons for shared state and logic.
Code
angular.module('servicesApp', [])
.factory('UserService', function() {
const users = [];
return {
add: function(user) { users.push(user); },
list: function() { return users; },
count: function() { return users.length; }
};
})
.service('AuthService', function($http) {
this.login = function(creds) {
return $http.post('/api/login', creds);
};
this.logout = function() {
return $http.post('/api/logout');
};
})
.controller('AppController', function(UserService, AuthService) {
const vm = this;
vm.users = UserService.list();
vm.addUser = function() {
UserService.add(vm.newUser);
vm.users = UserService.list();
};
});Explanation
Both factory and service produce singletons shared across the app; factory returns an object literal, while service uses 'this' as a constructor. Inject them by name into controllers (AngularJS resolves dependencies from parameter names unless minified—use $inject or array annotation). They are lazy-instantiated once per app lifetime.
More AngularJS Snippets
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Custom Directives
Attribute directive and element directive with isolated scope.
Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Custom Filters
Chainable filters for formatting values in templates.
Forms & Validation
Form with required, minlength, email validation, and disabled submit.