我正在尝试从我的服务器api获取一些json数据。网址是/联系人。 我收到有关未知提供商的错误,但我不明白我在这里做错了什么。我再次修改了代码,但似乎又发生了。
(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>
答案 0 :(得分:0)
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;
});
答案 1 :(得分:0)
您目前正在将联系人作为新模块注入:
var app = angular.module('test', ['ngRoute', 'Contacts', '$http']);
您不需要此,因为“联系人”是一项服务,也是同一模块的一部分。将此行更新为:
var app = angular.module('test', ['ngRoute', '$http']);
答案 2 :(得分:0)
问题是您正试图将$scope
注入service
。
Scope是应用程序控制器和视图之间的粘合剂。
请查看documentation。
而不是
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;
});
});