Joefers Joefers - 3 months ago 8
Javascript Question

Angular module functions: using var?

I'm pretty new to Angular, but a recent problem I debugged in my application went as follows:

Say I'm attaching a new directive to an existing module defined in another .js file. When I use the following syntax:

angular
.module('myApp')
.directive('ratingStars', ratingStars)
;

var ratingStars = function(){
return {
restrict: 'EA',
scope: {thisRating : '=rating'},
templateUrl: '/my.template.html'
};
};


I would get an error, along the lines of "Argument 'fn' is not a function, got undefined".

However, I could fix the code using the following (note the use of function directly rather than assigning to a var).

angular
.module('myApp')
.directive('ratingStars', ratingStars)
;

function ratingStars(){
return {
restrict: 'EA',
scope: {thisRating : '=rating'},
templateUrl: '/my.template.html'
};
}


What is the logical difference between taking my function and assigning to a var, rather than defining the function outright? Is some sort of variable hoisting going on? Is my var only local to that one file?

Thanks much.

R.J R.J
Answer

Its related to top hoisting.

What is the logical difference between taking my function and assigning to a var, rather than defining the function outright?

In the first script,

Your script is interpreted as follows.

var ratingStars;

angular
    .module('myApp')
    .directive('ratingStars', ratingStars);

ratingStars = function() {
    return {
        restrict: 'EA',
        scope: { thisRating: '=rating' },
        templateUrl: '/my.template.html'
    };
};

So,you can see,var ratingStars is declared first and assigned it to the directive definition.Its because variable in JavaScript declared using var is top hoisted at function scope which block scope. But actual definition will occur after that.

In the second script,

Your function definition,will defined at top of function scope which is block scope. So,it getting interpreted correctly.

So, first one used function expression where the variable getting top hoisted

but not actual function definition and second one uses function defination

where function defination itself getting top hoisted