1

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the answer. But now appear this error: Error: $injector:unpr Unknown Provider
@marcelo2605 did you change your controller code as I suggested..? could you paste whole console error here
Yes. Here is the error: Error: [$injector:unpr] errors.angularjs.org/1.4.1/$injector/…
@marcelo2605 you should also remove . from $routeProvider. when('/', { templateUrl: 'partials/home.html', controller: 'HomeCtrl' }). which is placed at the end
I remove the other conditions and forgot to remove ".". This is not the problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.