penguinsource
penguinsource

Reputation: 1200

angularjs calling a function from inside a controller

pokeApp.controller('mycontroller', function($scope, $routeParams){


   // part 1: // why would this not work
   $scope.myFunc();     

   $scope.myFunc = function(){
       console.log("Hi !");
   }

   // part 2: // why would this not work

  this.helloWorld();
  this.helloWorld = function(){
       console.log("Hello World");
  }
}

Hi My question is why would these 2 things not work; i mean either are either in the controller or in the scope. I know i can call a function simply defined 'function helloWorld(){...}'

thanks !

Upvotes: 0

Views: 54

Answers (3)

Shomz
Shomz

Reputation: 37711

You expected function hoisting to happen:

    myFunct(); 

    function myFunct() {
        alert('hey');
    }

this would work.

But this wouldn't:

myFunct(); 

var myFunct = function() {
    alert('hey');
}

The similar case is going on with the controller scope property, which behaves exactly as a regular variable in this case, means no hoisting happens.

You'll find some great explanations about hoising here: var functionName = function() {} vs function functionName() {}.


So, to make everything in your original code work using the hoisting feature, it should look like this:

pokeApp.controller('mycontroller', function($scope, $routeParams){


   // part 1:
   myFunc();     

   function myFunc(){
       console.log("Hi !");
   }

   // part 2:

  helloWorld();
  function helloWorld(){
       console.log("Hello World");
  }
}

Or, a little hacky way to maintain scopes:

pokeApp.controller('mycontroller', function($scope, $routeParams){


   // part 1:
   $scope.myFunc = myFunc; // this is the key, assigns a hoisted function value
                           // to the $scope object property which is then ready
   $scope.myFunc();     

   function myFunc(){
       console.log("Hi !");
   }

   // part 2:
  this.helloWorld = helloWorld;
  this.helloWorld();
  function helloWorld(){
       console.log("Hello World");
  }
}

Here's a snippet showing that in action:

    var myObj = {};
    myObj.f = myFunct;
    myObj.f(); 

    function myFunct() {
        alert('yay, it still works!');
    }

Upvotes: 1

SET001
SET001

Reputation: 11728

You can use hoisting to do this:

app.controller('MainCtrl', function($scope) {

  $scope.myFunc = myFunc;
  $scope.myFunc();

  function myFunc(){
    console.log("Hi !");
  }

});

plunk

Heare is good article about it - http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

P.S. Actually I can't see any reasons to do so in real practice...

Upvotes: 0

Charlie
Charlie

Reputation: 10307

You're calling the function before it has been defined. Change your code to:

   $scope.myFunc = function(){
       console.log("Hi !");
   }
   $scope.myFunc();   

Upvotes: 1

Related Questions