Why ng-app not ng-module?

前端 未结 3 2139
故里飘歌
故里飘歌 2021-02-18 16:25

I understand that ng-app initializes a module in AngularJS as follows:

var app = angular.module(\'myApp\', []);

B

相关标签:
3条回答
  • 2021-02-18 16:57

    ng-app means: That page has Angular in it!

    ng-app="module" means: That page has Angular in it and necessary controls/services/etc are defined in that module.

    0 讨论(0)
  • 2021-02-18 16:59

    I don't think Craig is asking what does ng-app do or how does it work.

    I think he's asking why did the people that created angular name that directive ng-app. Why didn't they name it ng-module. ng-module would be easier to understand.

    For example ng-controller should name a controller, ng-module should name a module. The angular methods to create them are named module() and controller(), there is no method or entity called "app".

    I tend to agree with Craig. That said if I were go speculate why they named it ng-app I would think it's because you are only allowed to have one ng-app directive in your HTML. If you wanted to have more than one module associated with your HTML page you can do it programmatically.

    So ng-app is more of a utility to bootstrap your HTML with a module, it is not a generic way to associate modules with your HTML.

    If you look at the documentation that's what it suggests:

    Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the or tags.

    Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other.

    http://docs.angularjs.org/api/ng/directive/ngApp

    All that said if you want an ng-module directive you could always write your own to wrap the angular.bootstrap() function. You can find more details and code about how to do this on a blog post I wrote about it: AngularJS: Getting around ngApp limitations with ngModule

    0 讨论(0)
  • 2021-02-18 17:03

    ng-app defines the main or bootstrap module of your application, which should perform the initialization task of your application. There may be case where at run time you want to decide what which should be the main module of your application. Like in java you have many methods and classes but you define one main method as starting point. Similarly, in angular you have many module, however, you define one module as the starting point of application.

    0 讨论(0)
提交回复
热议问题