Think of modules and dependency injection.
So let's say you have these three files
<script src="controllers.js"></script> <script src="services.js"></script> <script src="app.js"></script>
You will need three modules
1. The main application module
angular.module('MyApp', ['controllers', 'services']) .config(['$routeProvider', function($routeProvider){ $routeProvider .when('/bookslist', { templateUrl: 'partials/bookslist.html', controller: "BooksListCtrl" }) .otherwise({redirectTo: '/bookslist'}); }]);
Please note that the other two modules are introduced into the main module, therefore their components are available for the entire application.
2. Controller module
Currently your controller is a global function, you can add it to the controller module.
angular.module('controllers',[]) .controller('BooksListCtrl', ['$scope', 'Books', function($scope, Books){ Books.get(function(data){ $scope.books = data; }); $scope.orderProp = 'author'; }]);
Books is passed to the controller function and is provided by an accessible service module that has been added to the main application module.
3. Service module
This is where you define your Books service.
angular.module('services', []) .factory('Books', ['$http', function($http){ return{ get: function(callback){ $http.get('books.json').success(function(data) {
There are several ways to register services.
- service : the constructor function is passed (we can call it a class) and returns an instance of the class.
- provider : the most flexible and customizable as it gives you access to the injector call functions when creating a service instance
- factory : the function that the injector calls when creating the service instance is passed.
My preference is to use the factory function and just return the object. In the above example, we simply return the object using the get function, which receives a success callback. You can also change it to pass the error function.
Edit The response to the @yair request in the comments is here, how you should introduce the service into the directive.
4. Directive module
I follow the usual pattern, first add the js file
<script src="directives.js"></script>
Then define a new module and register the material, in this case the directive
angular.module('directives',[]) .directive('dir', ['Books', function(Books){ return{ restrict: 'E', template: "dir directive, service: {{name}}", link:function(scope, element, attrs){ scope.name = Books.name; } }; }]);
Deploy the directive module in the main module in app.js
angular.module('MyApp', ['controllers', 'services', 'directives'])
You might want to follow a different strategy and insert the module into the directives module
Note that the annotation for the syntax of inline dependencies is the same for almost everything. The directive introduces the same book service.
Updated by Plunker : http://plnkr.co/edit/mveUM6YJNKIQTbIpJHco?p=preview