ottercoder ottercoder - 5 months ago 7
Javascript Question

Call a function from function inside the same controller

So I'm trying to call a

function
from
another function
. And both of them defined inside the same
Controller
. But with everything I've tried so far it's
"funtion is not defined"
at the best. How to do this thing properly?

angular.module('App')

.controller('Controller', ['$http', '$scope', function($http, $scope) {

this.getSomething1 = function() {};

this.getSomething2 = function() {
if (1 == 1) {
getSomething1();
}
};
}]);



ReferenceError: getSomething1 is not defined

Answer

You need to call this.getSomething1() but there's a catch.

The problem here is that this inside the function is not always the same as this outside it. So to be safe, save the controller this in a variable and use that to call the function:

angular.module('App')

.controller('Controller', ['$http', '$scope', function ($http, $scope) {
    var vm = this;
    vm.getSomething1 = function () {
    };

    vm.getSomething2 = function ()  {
        if(1 == 1){
            vm.getSomething1();
        }
    };
}
]);

Another option that can make for much cleaner code is to always use named functions. You can still expose whichever of them need to be exposed on the controller but you can also call them directly.

angular.module('App')

.controller('Controller', ['$http', '$scope', function ($http, $scope) {
    angular.extend(this, { getSomething1: getSomething1, getSomething2: getSomething2 });
    return;

    function getSomething1() {
    };

    function getSomething2()  {
        if(1 == 1){
            getSomething1();
        }
    };
}
]);

This also has the benefit of separating the initialisation code at the top of the controller instead of scattering it through the function declarations.

The extend call looks even cleaner if you can use ES2016 syntax:

angular.extend(this, { getSomething1, getSomething2 });
Comments