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?
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.
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() {} ())
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(){})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With