/angularjs/

AngularJS, Service & Factory

2014-09-13 19:33:53

In this simple example you will learn how to create public and private function in service or factory.

angular.module('serviceFacadeTest')

    .factory('catFactory', function () {

        var getCatsPublic = function () {
            return [
                {},
                {}
            ];
        };

        var getCatPrivate = function () {
            return [
                {},
                {}
            ];
        };

        this.getCatThis = function () {
            return [
                {},
                {}
            ];
        }

        return {
            getCatsPublic: getCatsPublic
        };
    })

    .service('dogService', function () {

        var getDogsPrivate = function () {
            return [
                {},
                {}
            ];
        };

        this.getDogsPublic = function () {
            return [
                {},
                {}
            ];
        };
    })
;
console.log(catFactory.getCatsPublic()); // [Object, Object]
console.log(catFactory.getCatThis()); // TypeError: undefined is not a function
console.log(catFactory.getCatPrivate()); // TypeError: undefined is not a function

console.log(dogService.getDogsPublic()); // [Object, Object]
console.log(dogService.getDogsPrivate()); // TypeError: undefined is not a function