这是我的json:
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
我的javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function() {
$http({
method: 'POST',
url: 'serverUrl',
data: name.name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
我的HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction()">POST</button></td>
</tr>
</tbody>
我想要做的是当我点击按钮&#34; POST&#34; name.name发布到服务器。我在$http.post
中尝试postfunction()
,但我得到了#34; $ http未定义&#34;在控制台中。
答案 0 :(得分:3)
您忘记将$ http注入您的控制器
app.controller('FirstCtrl', function($scope, service, $http) {
^
答案 1 :(得分:2)
您必须在控制器'FirstCtrl'中注入$ http服务,如下所示:
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serverUrl',
data: name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
另外,除了将参数传递给post函数之外,还必须在HTML中传递'name',如下所示,这是因为,在你的控制器中,'name'永远不会被定义。
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction(name.name)">POST</button></td>
</tr>
</tbody>