Marshall Marshall - 2 months ago 11
AngularJS Question

How to make service calls using angular controller?

I'm facing a problem with angular JS Controller function. I have a controller and in that controller I have bunch of functions which are getting called from a service which contains HTTP get and post requests.

To be specific my question is inside a controller, when I try to write:

$scope.functionName = function()
{
//some code
}


My function doesn't get called at all. And when I do the following my function gets called but the scope goes undefined for rest of the functions.

app.controller("ControllerName", function ($scope, ServiceName) {
getAll();
getAppKey();
getAppDefaults();

function getAll(){//some code}
function getAppKey(){//some code}
function AppDefaults(){//some code
})


I'm not sure where I'm going wrong. I would really appreciate anyone's help who can help me out with this issue.

Answer Source

I think you are defining function with $scope and calling function without $scope. This code will work:

app.controller("ControllerName", function ($scope, ServiceName) {

    $scope.getAll = function{
        console.log("function called");
    }

    $scope.getAll();
})

And this code will not work as expected:

app.controller("ControllerName", function ($scope, ServiceName) {

    $scope.getAll = function{
        console.log("function called");
    }

    getAll();
})