Can you pass parameters to an AngularJS controller on creation?
Inject parameters during AngularJS controller initialization using the resolve
property in route configuration. For dynamic URL values, use $routeParams
. Here’s an example:
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:
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.
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:
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:
Structuring for success
Organize by splitting controllers into separate files:
Use module.value
or module.constant
to inject parameters that don't change often:
Mastering dependency injection and reusability
Aim for separation of concerns, employ constructor dependency injection for modular, maintainable, reusable code:
URL parameter tricks with $routeParams
Utilize $routeParams
to fetch URL parameters and $routeProvider
to nail your route configuration:
Was this article helpful?