Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...