Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-app without a value

Tags:

angularjs

Usually, you see Angular initialized on a page with a directive like ng-app="myModule", but it is valid to just use ng-app. However, as things like controllers are registered with myModule, is it ever useful at all to just use ng-app? Is there a way to register controllers etc. if you don't specify a module to ng-app="..."?

like image 543
Jez Avatar asked Jun 03 '15 13:06

Jez


1 Answers

Prior to Angular 1.3 (when you could define controllers on the global scope), Angular was able to automatically discover controllers that were defined globally.

As of Angular 1.3, all controllers have to be defined within a module, and thus, you'd get very limited functionality out of an ng-app without a module. It could potentially be beneficial for prototyping, but even there, you're not going to get much.

So, pre-angular 1.3 usage:

<div ng-app>
   <div ng-controller="SomeController">
       {{something}}
   </div>
</div>

You could define your javascript like this and it would work:

<script>
    function SomeController($scope) {
        $scope.something = "Hello";
    }
</script>

Edit:

As mentioned in the comments, you can still enable this behavior by using $controllerProvider.allowGlobals(). That said, the Angular team has tried to deter us from defining controllers this way from the start, and should be avoided:

NOTE: Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application [...]

like image 156
Tom Avatar answered Oct 22 '22 19:10

Tom