Angular gotcha: ng-app=”myApp” (named applications)

Angular is magical. The magic starts happening simply like so:

<html ng-app>
  <script src="angular.min.js"></script>
  There are {{ 1 + 2 }} apples in the basket.
</html>

Which outputs:

There are 3 apples in the basket.

However, when the magic stops you could be left tearing your hair out finding the correct potion!

For example, if you change ng-app to ng-app="myApp" you will see {{ 1 + 2 }} outputted instead of 3 with the following error:

ng-app-gotcha

OK, that kinda makes sense as we’ve not created a module named myApp.

Right, let’s do that:

<html ng-app="myApp">
  <script src="angular.min.js"></script>
  <script>
    var myApp = angular.module('myApp');
  </script>

  There are {{ 1 + 2 }} apples in the basket.
</html>

Hrm, well the magic still isn’t working! And we’re hit with a double whammy!

ng-app-gotcha-2

Digging a bit into what’s happening with angular.module. Apparently, its method signature is:

angular.module(name[, requires], configFn);

Where requires is optional, however, If specified then new module is being created. If unspecified then the the module is being retrieved for further configuration. Aha! So the second parameter is required if creating a module!

<html ng-app="myApp">
  <script src="angular.min.js"></script>
  <script>
    var myApp = angular.module('myApp', []);
  </script>

  There are {{ 1 + 2 }} apples in the basket.
</html>

Facepalm!

Note: All tests done with the current stable release of Angular version 1.0.6.

  • Melvina

    Great website you have here but I was wondering if you knew of
    any message boards that cover the same topics discussed in this article?
    I’d really love to be a part of group where I can get responses from other knowledgeable individuals that share the same interest. If you have any suggestions, please let me know. Many thanks!