user2153984
user2153984

Reputation: 193

How to add multiple controllers to one view in Angular JS route

For example, in this official tutorial, only ONE controller PhoneListCtrl is assigned to the view /phones. What if I have multiple controllers for this view?

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).

Thanks in advance!

Upvotes: 0

Views: 202

Answers (1)

user128268
user128268

Reputation: 126

There are plenty of ways to attack this concern.

  • You can use the ng-controller directive within a view:

    <div ng-controller="someOtherController">
        <input ng-model="propertyOfSomeOtherControllersScope" />
    </div>
    
    • You can use the angular-ui team's ui-router module. In short, this allows you to have multiple named views within a single "state", which are idiomatically like their "routes". Way too much going on with it to describe it in full here, but it's a great module for almost any project.

    • This is kind of the same as the first solution, but you could use ng-include to include another partial which explicitly declares its controller. Basically, in your main file: <div ng-include="'file2.html'"></div> and in file2.html: <div ng-controller="someOtherController"></div>.

These three things just jump right to mind, there are certainly other ways to go about this. And in some cases, you might want a directive instead of just another controller within a single view. Hopefully this gets you started in the right direction.

Upvotes: 1

Related Questions