2016-04-22 73 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

感謝哥們,U學習角速度很快! – Deadpool

1

您必須在您使用它的服務getName中注入$ http。

2

$ HTTP應該在服務,而不是控制

app.service( '的getName',函數($ HTTP){