Anton Lyhin
Anton Lyhin

Reputation: 1945

Angular unexpected behaviour. Self-executing function calls scope function

Working code sample.

Trivial markup:

<!DOCTYPE html>
<html ng-app="APP">
<head></head>
<body ng-controller="myController">

    <script src="angular.min.js"></script>
    <script src="controller.js"></script>
</body>
</html>

Trivial code sample:

angular.module('APP', []).controller('myController', function($scope) {

    $scope.test = function() {
        console.log('Weird behaviour!')
    }

    (function() {} ()); //if you comment self-executing function console will be empty

});

And really strange scope behaviour. Can you please explain why this happens?

Upvotes: 5

Views: 113

Answers (3)

vp_arth
vp_arth

Reputation: 14992

Other answer for semicolon-haters:

 $scope.test = function() {
   console.log('Weird behaviour!')
 }

 !function(){}();

It's general rule to escape your startline [/('s when you write semicolon-less style:

;[].forEach.apply(arguments, iterator)
;(function(){})()

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

As you added code write after $scope.test function, It has () to it. So because of that it is test function is considered as self executing function,

As @estus already said you could avoid that issue by ending your function code by ;.

Code

$scope.test = function() {
    console.log('Weird behaviour!')
}(function() {} ())

Upvotes: 4

Estus Flask
Estus Flask

Reputation: 222750

You've unintentionally made test scope method IIFE, and the current code is essentially

$scope.test = (function() {
    console.log('Weird behaviour!')
})(undefined)

While $scope.test itself will be undefined.

It should be

$scope.test = function() {
    console.log('Weird behaviour!')
};

(function() {} ());

Semicolons are precious.

Upvotes: 6

Related Questions