Reputation: 11755
I have a 'beginner' question. Why does this error out? I call the function in the code, but the function is defined further down.
AngularJS version:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 'Someone';
$scope.doStuff(); // run the defined function, but errors out
$scope.doStuff= function(){ // function definition
console.log('did something');
}
}
But this one works fine:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 'Someone';
$scope.doStuff = function(){
console.log('did something');
}
$scope.doStuff();
}
Upvotes: 2
Views: 1629
Reputation: 565
You're not declaring a new variable when you write $scope.doStuff = function () {...}, you're assigning a property, which does not get hoisted. at the time you call $scope.doStuff(), $scope looks like:
{
name: "Someone"
}
As you can see there's no "doStuff" property until the next line executes.
Upvotes: 6