AngularJS - 一个文件中的控制器和服务

时间:2015-03-15 12:45:40

标签: javascript angularjs dependency-injection

为什么这个简单的代码不起作用:

angular.module('menuApp', [])


.factory('menuService', function($http){

    var Menus = {};

    Menus.get = function() {
            return $http.get('/api/foods');
        };

    return Menus;

})

 .controller('menuCtrl', function($http, Menus){

var vm = this;
vm.headline = "Menu Card";


Menus.get()
    .success(function(data) {
        vm.menus = data;
    });

});

HTML:

<div ng-controller="menuCtrl as menu">
        <h1>{{menu.headline}}</h1>
        <p>Search by catergory:</p>
        <input type="text" ng-model="search.category">
        <div class="ui divider"></div>

        <div class="ui grid">
          <div class="four wide column" ng-repeat="menu in menu.menus | filter: search">
            <div class="ui segment">
                <h3>{{menu.category}}</h3>
                <h2>{{menu.name}}</h2>
                <p>{{menu.desc}}</p>
          </div>
        </div>
      </div>
    </div>

这是控制台错误:

  

错误:[$ injector:unpr] http://errors.angularjs.org/1.3.14/ $ injector / unpr?p0 = MenusProvider%20%3C-%20Menus%20%3C-%20menuCtrl       在错误(本机)       在https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417       在https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:38:7       在Object.d [as get](https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:36:13)       在https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:38:81       在d(https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:36:13)       at Object.e [as invoke](https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:36:283)       at $ get.w.instance(https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:75:451)       在https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:58:476       在s(https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:408

1 个答案:

答案 0 :(得分:0)

Angular将通过匹配工厂注册的名称来查找您的服务,因此您的控制器参数必须具有名称menuService

此外,如果您计划最小化代码,我建议您use array notation

您的控制器行应如下所示:

.controller('menuCtrl', ['$http', 'menuService', function($http, menuService){
...
}]);