6

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

1
  • There should be no issue in putting them in separate files, so long as you load them in the correct order (i.e. modules script first, and then the other two whose order doesn't matter) Commented Feb 24, 2015 at 13:25

1 Answer 1

17

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Your solution works fine... Originally I have var ipCharts = angular.module('ipCharts', []) in each file.
yes that is for creating new one, great to hear that it helped you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.