Balaji Gopal
Balaji Gopal

Reputation: 791

Multiple controller for same view in AngularJS?

Is there any way that I can define two controller for the same templateUrl in angularjs using stateProvider like below?

//State Provider for dashBoard Screen
.state('dashBoard', {
    cache : false,
    url : "/dashBoard",
    templateUrl : dashBoardHtml,
    controller : ["FirstController","SecondController"]
})

The data binding logic is to heavy in my controller, the number of line is more than 1000, I have optimised, reduced cyclometic complexity everything. But now to make it more modularize I need to split the controller without change in the view like by not using any nested views.

Is there any way to define multiple contollers to same templateURL/html?

Upvotes: 2

Views: 993

Answers (4)

pawan
pawan

Reputation: 19

your can assign controller on html

<div ng-controller="controller1"></div>

and on same HTML on other div

 <div ng-controller="controller2"></div>

Upvotes: 0

Abdullah Al Noman
Abdullah Al Noman

Reputation: 2878

This will work for you but if you want then you can use ng-controller directive as well

$stateProvider.state('view', {
    url: "/url",
    views: {
        'menuContent': {
            templateUrl: "template",
            controller: ['ctrl1', 'ctrl2']
        }
    }
});

example using diretive

    <div ng-controller="testController2">
            <!-- your view content -->
     </div>

    <div ng-controller="testController1">
            <!-- your view content -->
   </div>

Upvotes: 1

r1cdjuabna1djauk1u
r1cdjuabna1djauk1u

Reputation: 445

I think you can put them into several services for business logic or directives for UI logic to make your code more clear and tidy.

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

You can only assign one controller from the state and other one inside template like this

.state('dashBoard', {
    cache : false,
    url : "/dashBoard",
    templateUrl : dashBoardHtml,
    controller : FirstController
})

template

<div data-ng-controller="SecondController">
        <!-- your view content -->
    </div>

Upvotes: 0

Related Questions