[英]AngularJs Error : $http request though defined in controller
我有以下代碼,在其中我調用.php服務以返回數據,該數據以后將更新我的模型和視圖。 雖然,我在控制器中注入了服務名稱和http仍然給我錯誤。
HTML:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="changeIt()">Change Name</button>{{name}}
<script>
//Module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl', function($scope, getName, $http){
$scope.name = "Peter";
$scope.changeIt = function(){
getName.getTheName()
.success(function(data) {
$scope.name = data.name;
});
}
});
//Service Declaration
app.service('getName',function(){
return {
getTheName: function() {
return $http({
url: 'hello.php',
method: 'Post',
headers: {
'Content-Type': 'application/json'
}
});
},
}
});
</script>
</body>
</html>
PHP:
<?php
echo $data=json_encode(array('name'=>'Lara'));
?>
有人可以幫我解決這個問題嗎?
$ http應該在服務中定義,而不是在控制器中定義
app.service( '的getName',函數($ HTTP){
您必須將$ http注入到使用它的服務getName
中。
您也需要將其注入服務
app.service('getName',function($http){
return {
getTheName: function() {
return $http({
url: 'hello.php',
method: 'Post',
headers: {
'Content-Type': 'application/json'
}
});
},
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.