1

I recently started working on my first Angular JS project, and I want to make sure I'm handling Multiple dependance injection correctly. Any suggestions or feed back will be greatly appreciated!

var app = angular.module('app', [
  'ngRoute',
  'ngIdle',
  'ui.bootstrap'
]);

app.controller('testCtrl', [
  '$scope', '$http', '$timeout', '$location', 'SessionService',
  function($scope, $http, $timeout, $location, SessionService) {

  // Do Stuff
}]);
1
  • This way IMO is the most human-readable, and you need to define the initial array with the dependencies names, because if you want to minify your code angular still need to old references to the dependencies. Commented Jun 16, 2014 at 15:50

1 Answer 1

2

I imagine you're just wondering about syntax here, There are a few different ways:

MyAppModule.controller("MyCtrl",MyCtrl);
MyCtrl.$inject = ['$scope', '$http', '$timeout', '$location', 'SessionService'];
function MyCtrl($scope, $http, $timeout, $location, SessionService){
    //..do stuff
}

I like this way because it is pretty decoupled, and can be separated easily from angular, wrapped up in a !function(){}() will keep it out of the global space. This way is also the least work for the injector initialization.

Then there is the array syntax you have shown. That's nice if you like brackets (}])).

You can also forgo manually writing the string names and use a build tool like ngmin. Though you'd have to follow the guidelines for declaring your dependencies.

I wouldn't say there are any certain best practices associated with any of this, but its more of a preference.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome thanks. You were correct in assuming I'm just looking at syntax. I hate ugly code and poor syntax, so I just wanted to make sure I'm doing it correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.