Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS controller and Factory in separate files

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

//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

like image 852
Alan B Avatar asked Feb 24 '15 13:02

Alan B


1 Answers

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;
});
like image 81
A.B Avatar answered Sep 24 '22 14:09

A.B