javascript Angular JS 控制器和工厂在单独的文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28696960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular JS controller and Factory in separate files
提问by Alan B
Web development and Angular are completely new to me. I have created module , factory and controller in a same file (app.js). Below is the sample code
Web 开发和 Angular 对我来说是全新的。我在同一个文件 (app.js) 中创建了模块、工厂和控制器。下面是示例代码
//Main Module
var ipCharts = angular.module('ipCharts', []);
//Factory
ipCharts.factory('securityFactory', function ($http) {
var securities = {};
$http.get('api/Securities').
success(function (data, status, headers, config) {
securities = data;
}).
error(function (data, status, headers, config) {
// log error
});
var factory = {};
factory.getSecurities = function () {
return securities;
}
return factory;
});
//Controller
ipCharts.controller('securityController', function ($scope,securityFactory) {
$scope.securities = securityFactory.getSecurities();
});
I am wondering how module, factory and controller can be placed in separate files.
我想知道如何将模块、工厂和控制器放在单独的文件中。
I can place the controller in a separate file when the controller is not making any reference to the factory. I cant get it working when controller using the factory and the factory is in a separate file. Thanks
当控制器没有参考工厂时,我可以将控制器放在一个单独的文件中。当控制器使用工厂并且工厂位于单独的文件中时,我无法使其工作。谢谢
回答by A.B
Include your main app file (in which you create the module) above the controller and factory files.
在控制器和工厂文件上方包含您的主应用程序文件(您在其中创建模块)。
For retrieving pre-existing module:
检索预先存在的模块:
var ipCharts = angular.module('ipCharts');
For controller file:
对于控制器文件:
var ipCharts = angular.module('ipCharts');
ipCharts.controller('securityController', function ($scope,securityFactory) {
$scope.securities = securityFactory.getSecurities();
});
For Factory file:
对于工厂文件:
var ipCharts = angular.module('ipCharts');
ipCharts.factory('securityFactory', function ($http) {
var securities = {};
$http.get('api/Securities').
success(function (data, status, headers, config) {
securities = data;
}).
error(function (data, status, headers, config) {
// log error
});
var factory = {};
factory.getSecurities = function () {
return securities;
}
return factory;
});