简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM