Angular.js: creating services

And a quick post on how to create a service.

Angular service should contain code shared across controllers; code that doesn’t need to touch $scope directly – this is a controller’s job.

 To begin, declare a module, containing services:

angular.module('hubServices', [])
    .factory('adminHub', function () {
        function hubServc(){
            this.getUsers = function(){
               return [
                    {"name":"Bob"},
                    {"name":"Bill"}
                ];
            }
        };

        return new hubServc();
    });

This will declare a module named ‘hubServices’, with service named ‘adminHub’. Factory method can return anything (an object or a function (yeah, i know function is an object)), in this case I return an object with a single function.

In html, add this markup:

<ul ng-controller="OneController">
    <li ng-repeat="user in users">{{user.name}}</li>
</ul>
<script type="text/javascript">
    angular.element(document).ready(function () {
        angular.bootstrap(document, ['hubServices']);
    });


    function OneController($scope, adminHub) {
        $scope.users = adminHub.getUsers();
    }
</script>

 This will create a UL which uses the OneController function as a controller.

OneController function gets an instance of adminHub via angular’s dependency injection – note how the 2nd parameter name is same as the name provided to factory function, and how bootstrap contains name of a module.

 And that’s pretty much it.

See the results here: http://jsfiddle.net/etcoding/vAzb7/5/

Leave a Reply

Your email address will not be published. Required fields are marked *