2016-04-22 74 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){