-1

I have am new to Angular and messing around with Controllers. I created this simple controller function:

(function(){
var app = angular.module('store', []);

app.controller('StoreController', function(){
            this.product = gem;
});

    var gem = {
        name: "Dodecahedron",
        price: 2.95,
        description: '...'
        };    


})();

When I call this controller under my index.html, it works perfectly. Here is my index.html:

<html>

<head>

<script src = "angular.min.js"></script> <!--ANGULAR SOURCE-->
<script src = "app.js"></script> <!--APP SOURCE-->
<link rel = "stylesheet" href  = "bootstrap.css" type = "text/css"> <!--BOOTSTRAP-->

</head>

<body ng-app = "store">
<div ng-controller="StoreController as store">
    <h1>{{store.product.name}}</h1>
    <h2> {{store.product.price}} </h2>
    <p> {{store.product.description}} </p>
</div>

</body>


</html>

My code is working find and as expected. However, I don't get what the purpose of the last set of parentheses is in my controller function because once I take it out, my controller no longer works. It seems unnecessary, but for some reason my controller won't work without it. Could someone provide me with why this isn't working?

thanks!

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Mustafa
  • 337
  • 7
  • 14

1 Answers1

2

The whole

(function(){


})()

surrounding code is called a "self invoking function". Thus, omitting () just define a function and never calls it, so your angular app doesn't get its "store" module configured.

Its purpose here, is to create a scope so that the variable "app" and any other variable do not leak into the global (window) context.

If you use a module bundler like webpack which already add a local function context, then this become redundant. I assume it's useful for you because you have a script tag for every angular file in your app.

AlexG
  • 3,617
  • 1
  • 23
  • 19