IIFE in AngularJS IIFE in AngularJS angularjs angularjs

IIFE in AngularJS


There is a huge difference between this

($scope.myFunction = function(){ console.log('test'); }());

And this

($scope.myFunction = function(){ console.log('test'); })();

Because the first line assigns the result of the function call, and then only stores it, but it's not a function that it stores.

The second works as expected because you call the function after having assigned it to $scope.myFunction

UPDATE

As helpermethod pointed out in comments, the first line is not an IIFE, because you're not calling the function itself, but only the result of it.


Without seeing all of your code it is hard to tell. You are not using an IIFE, you are executing your own function and setting it to the $scope variable. Also, an IIFE will not make it run on page load. Instead of trying to correct all of that, try using code more like the example below.

Try creating a controller in an IIFE and updating your HTML like this:

<div ng-controller="MyCtrl as vm">     <select ng-options="vm.someOptions"         ng-model="vm.someModel"         ng-change="vm.myFunction()"></select></div>

and your controller

(function(){    angular.module('myapp').controller('MyCtrl', MyCtrl);    function MyCtrl() {        var vm = this;        vm.someModel;         vm.someOptions = []; // set these        vm.myFunction = myFunction;        activate();        function activate() {            myFunction();        }        function myFunction() {            // TODO: will be called onchange and            // when controller starts        }    }})();