Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
Anton Lyhin Avatar asked Nov 11 '15 19:11

Anton Lyhin


3 Answers

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.

like image 88
Estus Flask Avatar answered Nov 18 '22 14:11

Estus Flask


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() {} ())
like image 45
Pankaj Parkar Avatar answered Nov 18 '22 14:11

Pankaj Parkar


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(){})()
like image 1
vp_arth Avatar answered Nov 18 '22 13:11

vp_arth