olivier
olivier

Reputation: 2645

use multiple controllers in the same view with ionic

I have a view with the controller name "Listctrl" in this view i want to have a different controller named "LocationCtrl". At the moment i do this like this:

Routing

 .state('list', {
        url: '/list',
        templateUrl: 'templates/list.html',
        controller: "ListCtrl",
        cache: false
      })

HTML (list.html)

<ion-view ng-init="ini()" ng-controller="LocationCtrl">
  <ion-header-bar class="banner-top ext-box" align-title-h="left">
    <div class="int-box2"><h2 id="s_back1">STORIE</h2></div>
  </ion-header-bar>
<ion-content class="has-header has-footer no-bgColor start" overflow-scroll="false" has-bouncing="false">
<div class="container-list">

How should i solve this correctly? I need two controllers for the same view, but on different places, because i want to reuse the controller code in different views.

At the moment <ion-view ng-init="ini()" ng-controller="LocationCtrl"> does not run the LocationCtrl

Any help much appreciated!

Upvotes: 1

Views: 734

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105517

There is no possibility to have two controllers for one view, as this doesn't make sense. If you have a functionality that should be shared, use controller inheritance, but this is possible only if LocationCtrl adds its methods to $scope:

var app = angular.module('angularjs', []);

app.controller('LocationCtrl', function($scope) {
  // I have functionality to share
});

app.controller('ListCtrl', function($scope, $controller) {
  $controller('LocationCtrl', {$scope: $scope}); // This adds properties to ListCtrl's scope
});

Another approach could be to put ng-controller="LocationCtrl" to a wrapper div:

<ion-view ng-init="ini()">
  <div ng-controller="LocationCtrl">
       <ion-header-bar class="banner-top ext-box" align-title-h="left">
          <div class="int-box2"><h2 id="s_back1">STORIE</h2></div>
       </ion-header-bar>

But this doesn't seem like a good option. A better approach would be to create a component/directive with the functionality defined on LocationCtrl and use it somewhere in your view:

<ion-view ng-init="ini()">
  <component-with-location-ctrl-functionality></component-with-location-ctrl-functionality>

Upvotes: 1

Alexander Ilin
Alexander Ilin

Reputation: 26

If you are setting controller "ListCtrl" for the route, and you want to create place inside this route with another controller you can create directive with isolated scope

app.directive('yourNewDrctv', function() {
    return {
        restrict: 'E',
        templateUrl: 'yourNewTmpl.html',
        scope: {},
        controller: 'yourNewCtrl'
    };
});

and use it in your template "templates/list.html" anywhere just like that:

<your-new-drctv></your-new-drctv>

Upvotes: 0

Related Questions