Ways to declare Function in AngularJS Controller (controllerAs approach)

Elnaz picture Elnaz · May 24, 2016 · Viewed 39.6k times · Source

I use controller as approach instead of $scope. I have some problems with method calling from HTML. So, the question is that, how many ways exist in declare and call functions in this approach.

first: (If I want to do s.th. at first)

var vm= this ; 
vm.dataOne=[];

function funcOne() {
        myService.serviceFunc()
            .then(function (response) {
                vm.dataOne= response.data;
            });
    };
function activate() {
        funcOne();
        }
    activate();  

second: (If I want to initialize a variable based on a function returned value )

 vm.dataTwo = function () {
        doSomeThing();
 }  
  • Is there any way, too?
  • How should define a function in controller which will be called from HTML, as

    ng-click = "ctrl.dataTwo()";   
    

Answer

cst1992 picture cst1992 · May 24, 2016

Functions the way you've defined are private:

function functionOne() {

}; // Just function body, no need of semicolon

These are known as function declarations. Currently, they are only accessible within your controller.

To be able to call them, attach them to the controller so they become controller variables:

vm.functionOne = functionOne;

An advantage of this approach is that you can define functions after actually calling them, as opposed to how you do with $scope or $this. They are recognized via hoisting, and called.

About your initializing a returned value from a function, just call it:

vm.someVariable = someFunction();

Some references:

var functionName = function() {} vs function functionName() {}

Private Members in JavaScript

Angular Function Declarations, Function Expressions, and Readable Code

Angular Style Guide