user3115001
user3115001

Reputation: 404

Best practices to manage dependencies in Angular JS

I really enjoy the use of AMD to manage dependencies.

Now I'm getting started with Angular, in that case things become more complicated, because in one file we refer to a certain object that we admit to have already been created and this requires to make the script tags all organized and so on.

Another thing I noticed is that as the app grows there will be many script tags and more things to grant to be in order. I found ways to make AMD work with Angular.js, but I really didn't like it because it didn't seem natural.

What are the best practices to manage dependencies in Angular JS, making it easier to maintain the app as it grows?

Upvotes: 1

Views: 219

Answers (1)

ossek
ossek

Reputation: 1648

I'd suggest Require.js which does implement AMD. There's a great example of how to configure your main.js (the entry point for a require.js application) and test-main.js (entry point for karma tests) here: https://github.com/tnajdek/angular-requirejs-seed.

Notes:

  • make sure to use paths and shim for dependent modules that you want to expose to your application but that are not available as require.js modules.
  • make sure you keep in mind the distinction between angular.js's concept of modules and require.js modules. Require.js modules are about describing file dependencies and loading in the correct fashion. Angular modules are about enabling dependency injection, once this loading is done correctly. You'll end up with code that looks like this example:

example app.js

define([
    'angular', //as defined in the requirejs shim config
    'filters', //as defined in the filters.js
    'services', //as defined in services.js
    'directives', //in directives.js
    'controllers', //in controllers.js
    'angularRoute',//as defined in the requirejs config
    ],function(angular,filters,services,directives,controllers,angularRoute){

'use strict';
//angular.js module definition syntax: Declare app level module which depends on filters,services,controllers,directives, and angular globals
var angularappModule = angular.module('angularapp', [
  'ngRoute',
  'angularapp.filters',
  'angularapp.services',
  'angularapp.directives',
  'angularapp.controllers'
]);

angularappModule.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/angularapp', {templateUrl: 'partials/angularapp.html', controller: 'angularappCtrl'});
  $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
  $routeProvider.otherwise({redirectTo: '/angularapp'});
}]);

return angularappModule;
});


 

Upvotes: 1

Related Questions