gpt4 book ai didi

javascript - AngularJS - Controller 和服务在一个文件中

转载 作者:行者123 更新时间:2023-11-28 07:31:40 25 4
gpt4 key购买 nike

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

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>

这是控制台错误:

Error: [$injector:unpr] http://errors.angularjs.org/1.3.14/$injector/unpr?p0=MenusProvider%20%3C-%20Menus%20%3C-%20menuCtrl at Error (native) at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417 at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:38:7 at Object.d [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:36:13) at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:38:81 at 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) at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:58:476 at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:408)

最佳答案

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

另外,我推荐你use array notation如果您计划最小化代码。

您的 Controller 线路应如下所示:

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

关于javascript - AngularJS - Controller 和服务在一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com