[英]Angular injection (unknown provider)
我正在嘗試從服務器API中獲取一些json數據。 網址是/ contacts。 我收到有關未知提供程序的錯誤,但我不明白我在做什么錯。 我再次修改了代碼,但似乎又發生了。
(function() { var app = angular.module('test', ['ngRoute', 'Contacts', '$http']); app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when("/", { templateUrl: "partials/main.html", controller: "contactsCtrl" }) .otherwise({redirectTo:"/"}); }); app.service('Contacts', function($scope, $http) { this.data = null; this.all = function() { $http.get('/contacts'). success(function(data) { $scope.contacts = data; }) }; }); app.controller('contactsCtrl', function($scope, Contacts) { Contacts.all().query(function(data) { $scope.contacts = data; }); }); }());
<table class="table table-bordered"> <thead> <th>Firstname <input type="search" class="pull-right"></th> </thead> <tbody> <tr ng-repeat="contact in contacts"> <td> <a ng-href="/edit/{{ contact.firstname }}">{{ contact.firstname }}</a> </td> </tr> </tbody> </table>
Angular模塊通過將它們注入到您的應用程序中來工作。
var app = angular.module('test', ['ngRoute']);
您需要做的看起來像這樣。
var app = angular.module('test', ['ngRoute','http']);
這是我在我的項目中當前正在使用的http請求的示例。
var data = $.param({
workers: JSON.stringify({
user_name: "name",
password: "work",
email: "work@work"
})
});
$http.post("http://ec2-xx-x-xx-xx.compute-1.amazonaws.com/api/user/reg", data).success(function(data, status) {
$scope.user = data.user_name;
$scope.email = data.email;
$scope.access_token = data.access_token;
});
當前,您在這里將“聯系人”作為新模塊注入:
var app = angular.module('test', ['ngRoute', 'Contacts', '$http']);
您不需要此,因為“聯系人”是一項服務,並且是同一模塊的一部分。 將此行更新為:
var app = angular.module('test', ['ngRoute', '$http']);
問題是您正在嘗試將$scope
注入到service
。
范圍是應用程序控制器和視圖之間的粘合劑。
請看一下文檔 。
代替
app.service('Contacts', function($scope, $http) {
this.all = function() {
$http.get('/contacts').
success(function(data) {
$scope.contacts = data;
})
};
});
嘗試
app.service('Contacts', function($http) {
this.all = function() {
return $http.get('/contacts');
};
});
代替
app.controller('contactsCtrl', function($scope, Contacts) {
Contacts.all().query(function(data) {
$scope.contacts = data;
});
});
嘗試
app.controller('contactsCtrl', function($scope, Contacts) {
Contacts.all().then(function(data) {
$scope.contacts = data;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.