Ironluca Ironluca - 2 months ago 6
AngularJS Question

Does angular.controller always take anonymous function

I am fairy new to javascript as well as AngularJS. I have searched for an example where a already defined function can be passed during controller registration. For example, I am a bit unsure if I can register the 'firstTestControllerFunction' as the controller function.

var application=angular.module("AngularTest",[]);

function firstTestControllerFunction($scope) {

$scope.message="Message from First Test Controller";

}//firstControllerFunction closing


I am not sure, since my knowledge in this area is limited, could I do application.controller("MyController",|use the existing 'firstTestControllerFunction'|). Any help or pointing to the right direction would be sincerely appreciated.

Answer

When you are defining the controller you can use either anonymous function or use already defined function. The key is to use the function name, and not to invoke in your declaration. This code would be invalid:

// INVALID! you should not invoke the function firstTestControllerFunction
application.controller("MyController", firstTestControllerFunction())   

However this code if perfectly valid:

var application=angular.module("AngularTest",[]);

function firstTestControllerFunction($scope) {
    $scope.message="Message from First Test Controller";
}

application.controller("MyController", firstTestControllerFunction).