Angular unexpected behavior. The self-service function calls the scope function

Sample working code.

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> 

Example trivial code:

 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 weird behavior. Could you explain why this is happening?

+5
source share
3 answers

You have inadvertently implemented a test scope IIFE method, and the current code is essentially

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

So far, $scope.test will be undefined .

It should be

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

Semicolons are precious.

+6
source

When you added the code after the $scope.test function, it has () . Therefore, because of this, the test function is considered as self , executing the function ,

As @estus already said, you can avoid this problem by ending your functional code on ; .

code

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

Another answer for semicolons:

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

This is a rule to avoid your starting line [ / ( when you write a style with a semicolon:

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

Source: https://habr.com/ru/post/1235731/


All Articles