Search code examples
angularjsgulpcoffeescript

AngularJS module and controller in different files


I would like to move my controllers to it's own files while having module configuration file in separate file

For now I have this code:

# Module part
voucherModule = angular.module(
    'Backoffice.Vouchers'
    [
        'Core.Repository.Voucher'
        'ui.router'
    ]
)

voucherModule.config ($stateProvider) ->
    $stateProvider
        .state 'vouchers',
        url: '/vouchers'
        data:
            title : 'Vouchers'
        views:
            "main":
                controller: 'VoucherListController'
                templateUrl: 'views/vouchers/voucher-list.html'

# Controller part. Below should go to different file.

class VoucherListController extends BaseController
    @register voucherModule
    @inject '$scope', '$state', '$rootScope', 'VoucherRepository'

I have lots of .coffee files that are compiled to single file using gulp.

When I cut out controller code and simply move it to different file, I get following error:

Error: [$injector:modulerr] Failed to instantiate module Backoffice.App due to:
[$injector:modulerr] Failed to instantiate module Backoffice.Shop due to:
[$injector:nomod] Module 'Backoffice.Shop' is not available! You either misspelled the module name or forgot to load it.

As you can see it's even not related module error. I see that compiling is different this time:

--- BEFORE ---
var VoucherListController, voucherModule;

voucherModule = angular.module('Backoffice.Vouchers', ['Core.Repository.Voucher', 'ui.router']);
voucherModule.config(function($stateProvider) {
  return $stateProvider.state('vouchers', {/*..*/});
});

VoucherListController = (/* controller-code */)(BaseController);

--- AFTER ---
var VoucherListController;

VoucherListController = (/* controller-code */)(BaseController);

var voucherModule;
voucherModule = angular.module('Backoffice.Vouchers', ['Core.Repository.Voucher', 'ui.router']);
voucherModule.config(/*..*/);

Gulp file task:

gulp.task('build-core', function () {
    return gulp.src(sources.coffee.core) // AngularCore/**/*.coffee
        .pipe(continueOnError(coffee({bare:true})).on('error', gutil.log))
        .pipe(concat('core.js'))
        .pipe(gulp.dest(destinations.javascript.core)) // app/js/lib/
});

Can someone help me to figure out what is wrong? Basically module and controller code switches places and var position moves.


Solution

  • As Izagkaretos told, I just had to split path to multiple parts in gulp config, and then everything works fine.

    gulp.task('build-core', function () {
        return gulp.src(sources.coffee.core) // [AngularCore/**/*Module.coffee, AngularCore/**/*.coffee]
            .pipe(continueOnError(coffee({bare:true})).on('error', gutil.log))
            .pipe(concat('core.js'))
            .pipe(gulp.dest(destinations.javascript.core)) // app/js/lib/
    });