Explain Codes LogoExplain Codes Logo

Can you pass parameters to an AngularJS controller on creation?

javascript
angularjs
dependency-injection
promises
Alex KataevbyAlex Kataev·Jan 31, 2025
TLDR

Inject parameters during AngularJS controller initialization using the resolve property in route configuration. For dynamic URL values, use $routeParams. Here’s an example:

app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/user/:userId', { resolve: { userData: ['$route', 'UserService', function($route, UserService) { // Here's where the magic happens ✨ return UserService.getUser($route.current.params.userId); } ] }, controller: 'UserController' }); }]); app.controller('UserController', ['$scope', 'userData', function($scope, userData) { // Voila! Here's your user data $scope.user = userData; }]);

This approach ensures that the controller initializes with required data pre-loaded.

The convenient ng-init route

To initialize a controller with parameters, ng-init is a quick and handy tool:

<div ng-controller="MyController" ng-init="init('Eureka!')"></div>
app.controller('MyController', ['$scope', function($scope) { $scope.init = function(secretMessage) { // Revealing the secret 🕵️‍♀️ $scope.message = secretMessage; }; }]);

Take note though, ng-init should ideally be limited to aliasing complex expressions for the sake of legibility.

Advanced tactics with $attrs and $resource

Seeking more control? Use $attrs to read element attributes straight from DOM, and handle errors during initialization.

app.controller('MyController', ['$scope', '$attrs', function($scope, $attrs) { if ($attrs.myParam) { // Found it! 🎉 $scope.param = $attrs.myParam; } else { // Oops, we got a problem 🚨 throw new Error('myParam attribute is required, or else...'); } }]);

In turbocharging your API calls during controller initialization, $resource is your best buddy.

What about module.value and Service?

Employing app.value() gives an option to define initial parameters. Then services further streamline and modularize initialization:

// Defining an initial parameter, just because we can app.value('initialParam', 'The chosen one'); // Defining a service for more sophisticated initialization app.service('InitService', ['initialParam', function(initialParam) { // Let's jazz this up 🎷 this.data = initialParam; }]); // Injecting the value and service into the controller app.controller('MyController', ['$scope', 'InitService', function($scope, InitService) { $scope.init = function() { // Aaand it's a home run $scope.param = InitService.data; }; }]);

Manually initialize with angular.bootstrap

If you have multiple AngularJS applications on a page, angular.bootstrap allows you to manually initialize them with configuration data:

angular.module('myApp', []); // Configuration data, prepped and ready to be dispatched var configData = { key: 'Ready set go' }; // Manually firing up the application angular.element(document).ready(function() { angular.bootstrap(document, ['myApp']); });

Structuring for success

Organize by splitting controllers into separate files:

// app.js angular.module('myApp', []); // separate file, because tidiness matters // controller.js angular.module('myApp').controller('MyController', [...]);

Use module.value or module.constant to inject parameters that don't change often:

angular.module('myApp').value('configParam', 'Pink unicorn dancing');

Mastering dependency injection and reusability

Aim for separation of concerns, employ constructor dependency injection for modular, maintainable, reusable code:

// Look mom, I'm doing dependency injection! app.controller('MyController', ['configParam', function(configParam) { // Doubling up as a config keeper this.config = configParam; }]);

URL parameter tricks with $routeParams

Utilize $routeParams to fetch URL parameters and $routeProvider to nail your route configuration:

app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/item/:itemId', { templateUrl: 'item.html', controller: 'ItemController' }); }]); app.controller('ItemController', ['$scope', '$routeParams', function($scope, $routeParams) { // Your itemId coming right up! 🍽️ $scope.itemId = $routeParams.itemId; }]);