2016-04-22 22 views
0

次のコードがあります。このモデルでは、.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')); 
?> 

誰かが問題を私を助けることはできますか?

答えて

1

で定義する必要がありますサービスもあります

app.service('getName',function($http){ 
      return { 
       getTheName: function() { 
        return $http({ 
         url: 'hello.php', 
         method: 'Post', 
         headers: { 
          'Content-Type': 'application/json' 
         } 
        }); 
       }, 
      } 
     }); 
+0

ありがとうございました。 – Deadpool

1

あなたが使用しているサービスgetNameに$ httpを注入する必要があります。

2

$ HTTPサービスではなく、あなたがそれを注入する必要がありますコントローラ

app.service( 'のgetName'、関数($ HTTP){

関連する問題