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

如何创建单独的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浏览器控制台中抛出一个错误,说它无法找到我的控制器。任何提示?


PIPIONE
浏览 728回答 3
3回答

侃侃无极

文件一: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-seedhttp://briantford.com/blog/huuuuuge-angular-apps.html

DIEA

在末尾使用带有数组的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在没有数组的情况下使用它实际上是一个getter函数。因此,要分离您的控制器,您可以: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.jsangular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);在你的javascript导入过程中,只需确保myApp.js在AngularJS之后,但在任何控制器/服务/等之前...否则angular将无法初始化你的控制器。

犯罪嫌疑人X

虽然这两个答案在技术上都是正确的,但我想为此答案引入不同的语法选择。这个imho可以更容易地阅读注射的内容,区分等。文件一// Create the module that deals with controllersangular.module('myApp.controllers', []);文件二// Here we get the module we created in file oneangular.module('myApp.controllers')// We are adding a function called Ctrl1// to the module we got in the line above.controller('Ctrl1', Ctrl1);// Inject my dependenciesCtrl1.$inject = ['$scope', '$http'];// Now create our controller function with all necessary logicfunction Ctrl1($scope, $http) {  // Logic here}文件三// Here we get the module we created in file oneangular.module('myApp.controllers')// We are adding a function called Ctrl2// to the module we got in the line above.controller('Ctrl2', Ctrl2);// Inject my dependenciesCtrl2.$inject = ['$scope', '$http'];// Now create our controller function with all necessary logicfunction Ctrl2($scope, $http) {  // Logic here}
打开App,查看更多内容
随时随地看视频慕课网APP