Let's take an example where we create a factory called Users
and include all User-related API functions inside it:
'use strict';
angular
.module('todoListApp')
.factory('Users', usersFactory);
function usersFactory($http) {
var service = {
get: getUsers,
//edit: edit ...
};
return service;
function getUsers() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
The next step is to inject this factory wherever you need to use it.
In your controller, you would essentially do the following:
angular.module('todoListApp', [])
.controller('MainController', function($scope, Users) {
//.....
function loadUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
loadUsers();
//...
You can repeat this process by creating appropriate services for notes and projects as well.
To keep the main app.js file clean, move these services into separate files like users.service.js
. I also recommend moving controllers into separate files too.
When attaching a service/factory/controller within a separate file to the module, remember to do this:
angular.module('todoListApp').anything
Additionally, instead of using location.reload
to update the view with new data after editing or deleting a User, call loadUsers()
in the then()
section of those operations.
I hope this explanation makes sense!
PS: For more guidance on Angular development, consider checking out the styleguide by John Papas, which has been very helpful to me.