javascriptangularjsionic-v1

add controller to a template menu in ionic1


I have an application made in ionic1 and my application contains a template called menu.html and it contains a<ion-side-menus>which is loaded with my other templates and views. the issue is that I want my variables in the $scope can be seen directly in my template menu.html depending on the driver that is currently loaded.

for example in my controller actual I have:

$scope.title="hello";

in menu.html:

{{title}} (should be display "hello")

but my $scope variables are not shown in menu.html if I add ng-controller = "myControllerController" it works, but I want to avoid this solution, since the contents of my controller will be loaded twice. and I've done the test putting a console.log ("it loads") and this message appears two times. I need that the $scope of menu to be according to the current controller.

this is my code:

menu.html:

<ion-side-menus enable-menu-with-back-views="false">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon"  menu-toggle="left" >
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu id="sidemenu"  side="left"  >
    <ion-header-bar class="bar-stable">
      <h1 class="title">{{title}}</h1>  <!-- title -->
    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item menu-close href="#/app/productos">
          Registro
        </ion-item>
        <ion-item menu-close href="#/app/buscar">
          Buscar
        </ion-item>
        <ion-item menu-close href="#/app/ubicaciones">
          UbicaciĆ³n
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

controller actual: myControllerController.js

tinApp.controller('myControllerController', function($scope) {
 $scope.title="hello";
});

App.js:

.state('app', {
 url: '/app',
 abstract: true,
 templateUrl: 'templates/menu.html'
})

.state('app.view1', {
url: '/view1',
views: {
  'menuContent': {
    templateUrl: 'templates/view1.html',
    controller: 'myControllerController'
  }
}
})

Solution

  • Why not add an event listener to your menu controller that will fire every time a page changes. You can then get the page name every time and use that to set the title. And if its a custom name just add it as one of the pages custom parameters in the route.

    $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
            ...
        });