1

In AngularJS, I have two lengthy controllers, which are identical - except for one variable definition at the top (which is used in multiple places throughout the controller to decide what to process).

How can I consolidate these two controllers into only one controller?

Is there something like a controller factory that can take in an argument (my variable)?

Can you pass a variable to a controller, when specifying it in the router? Can you pass a variable when manually calling a controller via ng-controller in the html?

Something like this:

ControllerA
{
    mode = 'A';
    MakeControllerRealAndUseItInsteadOfCurrentController(mode);
}

ControllerB
{
    mode = 'B';
    MakeControllerRealAndUseItInsteadOfCurrentController(mode);
}

ControllerReal( mode )
{
    mode = mode;
    // actual controller content
}

1 Answer 1

3

Controller in Angular are tightly bound to the view they interact with and in fact the view has declaration of ng-controller based on which controller is instantiated. Controllers are not utility functions that can be shared across the app\views. Since the controller are doing similar function, it maybe the case that the views are pretty similar.

Some of the ways that you can reuse the controller code would be

  • Refactor any code that does not directly affect the view into service and call the service from your controllers.
  • If the view are similar may be look at reusable directives, with their own controllers, for create a specific part of your view, which can be used across views.
  • For the point above you can also create partial templates which can have their own controller, and reuse them using ng-include.
Sign up to request clarification or add additional context in comments.

2 Comments

I managed to combine the two views into one (which takes a different routeParam for each mode). Based on that, I could then also use this routeParam to combine the two controllers into one.
Great that i could be of some help here :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.