Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angularjs - Using ng-app without a value

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="..."?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 [...]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...