AngularJS的" .module("modulename",[…])"中的方括号是什么意思?

What is the meaning of the square brackets in “.module("modulename", […])” of AngularJS

本文关键字:方括号 意思 是什么 module modulename AngularJS      更新时间:2023-09-26

我刚刚看到了一个在AngularJS中路由的例子。我想知道在语法var mainApp = angular.module("mainApp", ['ngRoute']);中依赖项'ngRoute'和模块mainApp之间的关系。

前面我看到过在模块声明中使用空方括号的例子。

下面是整个代码的上下文:

var mainApp = angular.module("mainApp", ['ngRoute']);
  mainApp.config(['$routeProvider',
     function($routeProvider) {
        $routeProvider.
           when('/addStudent', {
              templateUrl: 'addStudent.htm',
              controller: 'AddStudentController'
           }).
           when('/viewStudents', {
              templateUrl: 'viewStudents.htm',
              controller: 'ViewStudentsController'
           }).
           otherwise({
              redirectTo: '/addStudent'
           });
     }]);

在angular中,当定义module(创建它)时,您将它所依赖的其他module的名称作为数组(在方括号中)传递给它。

在你的例子中,mainApp - module依赖于ngRoute - module,使得ngRoute的组件(指令,服务,工厂,值…)可用于mainApp组件的依赖注入。要定义一个不依赖于任何其他模块的module,你需要传递一个空数组([])。参见angular文档了解更多关于模块的信息

[...]定义了一个数组

mainApp是一个主模块(主数组),ngRoute是一个子模块(类似对象数组)。

样本

var ngRoute=[];//{}
var mainApp=[ngRoute];// now the `mainApp` includes the `ngRoute`