如何创建独立的AngularJS控制器文件?

14 浏览
0 Comments

如何创建独立的AngularJS控制器文件?

我有一个AngularJS控制器的文件controllers.js。这个文件的结构如下:

angular.module('myApp.controllers', [])
  .controller('Ctrl1', ['$scope', '$http', function($scope, $http) {    
  }])
  .controller('Ctrl2', ['$scope', '$http', function($scope, $http) }
  }])

我想把Ctrl1和Ctrl2放到不同的文件中。 然后我会在我的index.html文件中包含这两个文件,但是应该如何组织呢?我尝试过类似于这样的一些事情,它会在Web浏览器控制台中抛出错误,说找不到我的控制器。有什么提示吗?

我在StackOverflow上搜索并找到了这个类似的问题——然而,这个语法是在Angular之上使用不同的框架(CoffeeScript),所以我无法跟进。


AngularJS:如何在多个文件中创建控制器

admin 更改状态以发布 2023年5月24日
0
0 Comments

使用带有数组结尾的angular.module API会告诉angular创建一个新的模块:

myApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

如果不使用数组,则实际上是一个获取函数。因此,您可以将控制器分离:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

在javascript导入时,只需确保myApp.js在AngularJS之后但在任何控制器/服务/等之前...否则angular将无法初始化您的控制器。

0
0 Comments

文件一:

angular.module('myApp.controllers', []);

文件二:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){
}]);

文件三:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){
}]);

按照这个顺序包含。我建议使用3个文件,这样模块声明就可以自己独立出来。


至于文件夹结构,有很多很多关于这个问题的观点,但是这两个是相当不错的

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html

0