0

I have following code, in which I am calling a service of .php to return data which will later update my model & view. Though, I injected the service name and http in the controller still it gives me error.

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'));
?>

Can someone help me out the problem?

3 Answers 3

2

$http should be defined in the service, not the controller

app.service('getName',function($http){

Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to inject it in service too

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

Comments

1

You have to inject $http in the service getName where you are using it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.