I need to have a set of resource factories to consume a rest api and use that in all of my modules and controllers. I'm confused as to how this should be separated and how to access the factories from controller.
As an example, let's assume I have:
// rest.js
angular.module('myApp.rest', ['ngResource'] )
.factory('Book', function ($resource) {
return $resource('api/book', {}, {
getBook: {
method: 'GET'
},
});
})
Here's the main module as myApp
:
// app.js
angular.module('myApp', [
'ngRoute',
'ngResource',
'app.rest',
'app.library'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/book', {
templateUrl: 'someTemplate',
controller: 'LibraryCTRL',
});
Now I want to have another module called app.library
which can use Book
resource. How the Dependency Injection would look like?
More important question: Is this the right way to do it? I mean is it better to attach the whole Book
factory to myApp
or use a separate myApp.rest
module?
// library.js
angular
.module('myApp.library', ['ngResource']) // INJECT REST MODULE HERE?
.controller('LibraryCtrl', Library);
// INJECT BOOK RESOURCE HERE?
Library.$inject = [];
// USE BOOK IN THIS CONSTRUCTOR
function Library() {
var vm = this;
// USING IT
Book.getBook(function(data){
vm.book = data;
});
}