Black Mamba
Black Mamba

Reputation: 15595

How to do dependency injection in multiple controller in a single step

I'm using ionic1 and I have multiple controller each one is for different page. Consider the following injections:

.controller('login', function($scope, $http, $location, $state,$rootScope , auth,$timeout)
.controller('Home', function($scope, $rootScope, $http, $state,$location, $ionicNavBarDelegate, $timeout, auth, getData)

So on I have about 10 of them. Most of the injections are common to all the controllers such as $scope,$rootScope and few others. So I want to know if there is a one liner to inject all the dependencies in one go.

Upvotes: 2

Views: 378

Answers (2)

Founded1898
Founded1898

Reputation: 977

You could create a factory which returns some of the most used dependencies.

Something like this:

angular
  .module('app')
  .factory('common', common);

common.$inject = ['$rootScope', '$http', '$state'];

function common($rootScope, $http, $state) {
  var service = {
    $rootScope: $rootScope,
    $http: $http,
    $state: $state
  };

  return service;
}

then you just need to include the common service in your controller and use it like this: common.$rootScope.

Hope this helps :)

Edit As @estus said in the comments, with $scope it would fail because $scope is a local dependency and not available in services/factories. This should not be an issue since I would recommend to avoid $scope as far as possible (use controllerAs syntax)

Upvotes: 3

Estus Flask
Estus Flask

Reputation: 222626

Injecting all dependencies contradicts the concept of dependency injection (besides the fact that controllers can have local dependencies). A dependency is what a controller depends on.

If there are several controllers that have matching dependencies, they can inherit base controller. If child controllers should have their own dependencies, this can be done with base class that automatically assigns dependencies to controller instance. Controller inheritance works best with ES6 classes:

class BaseController {
  static get $inject() {
    return ['$rootScope', '$scope', '$timeout'];
  }

  constructor(...deps) {
    this.constructor.$inject.forEach((depName, i) => {
      this[depName] = deps[i];
    });
  }
}


class SomeController extends BaseController {
  static get $inject() {
    return [...super.$inject, 'some'];
  }

  constructor(...deps) {
    super(...deps);
    ...
  }
}

app.controller('SomeController', SomeController);

Upvotes: 1

Related Questions