Search code examples
htmlangularjsangularjs-ng-routeangular-controller

Edit HTML outside ng-view on route change


I want to change some HTML in the navbar upon a route change, using the routing information. I can almost get it to work with the code below, but the data is not parsed as HTML when arriving in the DOM. I tried using the $sce service, but that didn't really get me anywhere.

If there are any other (better) ways of editing the HTML on route change, then please let me know.

HTML:

<nav>
  <div ng-controller="BrandCtrl">
    <div class="nav-brand">
      {{brand}}
    </div>
  </div>
</nav>

<div ng-view></div>

JS:

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

app.controller("BrandCtrl", function($scope, $route) {
  $scope.$on('$routeChangeSuccess', function() { 
    var html = $route.current.html;
    $scope.brand = html;
  });
});

app.config(function ($routeProvider) {
  $routeProvider
  .when('/next-page', {
    templateUrl: 'partials/next-page.html',
    controller: 'BrandCtrl',
    html: '<h3>New brand</h3>'
});

Solution

  • You should be changing the HTML via the 'views' in the routes.

     $stateProvider.state('app',{url: 'someurl',   
        views: {
          'topnav': { templateUrl: 'path/to/some/html',
                controller: 'navcontroller'},
          'mainContent': {templateUrl: 'path/to/some/other/html',
                controller: 'contentcontroller'}    } 
     });
    

    In your HTML you would have multiple views:

     <div ui-view="topnav"></div>   
     <div ui-view="mainContent"></div>