为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PIPIONE 2019-08-06 13:18:34
如何创建单独的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浏览器控制台中抛出一个错误,说它无法找到我的控制器。任何提示?
查看完整描述

3 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

文件一:

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


查看完整回答
反对 回复 2019-08-06
?
DIEA

TA贡献1820条经验 获得超2个赞

在末尾使用带有数组的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.js

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

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


查看完整回答
反对 回复 2019-08-06
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

虽然这两个答案在技术上都是正确的,但我想为此答案引入不同的语法选择。这个imho可以更容易地阅读注射的内容,区分等。


文件一


// Create the module that deals with controllers

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

文件二


// Here we get the module we created in file one

angular.module('myApp.controllers')


// We are adding a function called Ctrl1

// to the module we got in the line above

.controller('Ctrl1', Ctrl1);


// Inject my dependencies

Ctrl1.$inject = ['$scope', '$http'];


// Now create our controller function with all necessary logic

function Ctrl1($scope, $http) {

  // Logic here

}

文件三


// Here we get the module we created in file one

angular.module('myApp.controllers')


// We are adding a function called Ctrl2

// to the module we got in the line above

.controller('Ctrl2', Ctrl2);


// Inject my dependencies

Ctrl2.$inject = ['$scope', '$http'];


// Now create our controller function with all necessary logic

function Ctrl2($scope, $http) {

  // Logic here

}


查看完整回答
反对 回复 2019-08-06
  • 3 回答
  • 0 关注
  • 724 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信