angular.module
Usually when developing software, there is always a main which represents the point of entry for the program. Main is the starting point where you import/include the rest of your program.
However, for Angular, we have module, which kind of acts as main. It is a container for different part of your web.
1 |
angular.module( 'userService', [] ) |
name of the module – userService
array of other modules that your module may need – []
In this example, we are creating module userCtrl, which uses module userService
1 2 |
angular.module('userCtrl', ['userService']) { ..... |
Angular Services
Services are written as a module to be provided for controllers to be use.
Notice that we first declare ‘userService’ as part of the module. It does not rely on any other modules, hence the empty array parameter.
It simply gets the $http variable and uses its HTTP verbs to retrieve information from the web service urls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
angular.module('userService', []) .factory('User', function($http) { // create a new object var userFactory = {}; // get a single user userFactory.get = function(id) { return $http.get('/api/users/' + id); }; // get all users userFactory.all = function() { return $http.get('/api/users/'); }; // create a user userFactory.create = function(userData) { return $http.post('/api/users/', userData); }; // update a user userFactory.update = function(id, userData) { return $http.put('/api/users/' + id, userData); }; // delete a user userFactory.delete = function(id) { return $http.delete('/api/users/' + id); }; // return our entire userFactory object return userFactory; }); |