Search code examples
angularjsiife

Inserting module with controller in function AngularJS


why if I insert angular module with controller into function, angularjs stop working?

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

      app.controller("c1", function($scope){

          $scope.name = "Hello World!";

      });  
 });

Solution

  • You neglected the code of the IIFE (parenthesis at the end: () ).

    Below there is a snippet with your sample corrected.

    (function() {
      var app = angular.module("app", []);
    
      app.controller("c1", function($scope){
    
      $scope.name = "Hello World!";
    
      });  
    })(); //<< -- here!! See the closing ()
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app" ng-controller="c1">
    {{name}}
    </div>

    You can read more about IIFE here: