javascriptangularjsdependency-injectionangularjs-controllerangularjs-factory

AngularJS : Using factory inside a controller


This is my first attempt to use the Angularjs and I'm trying to create a service and use it inside a controller:

var appTest = angular.module("appTest", ["ngRoute"]);
var appTestControllers = angular.module('appTestControllers', []);

appTest.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {

        $routeProvider.
            when('/', {
                templateUrl: 'partials/home.html',
                controller: 'HomeCtrl'
            });

            $locationProvider.html5Mode(false);
    }
]);

appTest.factory("booksApi", function($http){

    var _getBooks = function() {
        return $http.get('http://localhost/editora-voo/website/books.json');
    };

    return{
        getBooks: _getBooks
    };

});


appTest.controller('HomeCtrl', ['$scope', '$http', function($scope, $http, booksApi) {

    booksApi.getBooks().success(function(data) {
        $scope.books = data;
    });
}]);

But it is returning an error: Cannot read property 'getBooks' of undefined


Solution

  • You missed to add booksApi depnedency inside your controller dependency array, You should add it first and then use that inside the function of controller.

    Controller

    appTest.controller('HomeCtrl', ['$scope', '$http', 'booksApi', //<--missed dependency here
      function($scope, $http, booksApi) {
        booksApi.getBooks().then(function(response) {
            $scope.books = response.data;
        });
    }]);
    

    Plunkr Here