Why ng-app not ng-module?

前端 未结 3 2180
故里飘歌
故里飘歌 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: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

提交回复
热议问题