简体   繁体   English

AngularJS:在控制器内部使用工厂

[英]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: 这是我第一次尝试使用Angularjs,我正在尝试创建一个服务并在控制器中使用它:

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 但它返回一个错误:无法读取未定义的属性'getBooks'

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. 您错过了在控制器依赖项数组中添加booksApi depnedency,您应该先添加它然后在控制器的函数内使用它。

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 Plunkr在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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