ankitdadhich ankitdadhich - 1 year ago 151
AngularJS Question

how to set header for each page using component in Angular 1.5

I started with Angular 1.5 component recently.
I am having various pages in my application. So I decided to create a

component which am using inside
As you see in navbar I have First, Second as navigation links. In my application there will be more parent child combinations.

I want to set title of each page by two way.

  1. By giving it in partial
    (see 1.html or 2.html)

  2. Also I would like to set it from controller as well.
    vm.title = "current page title"
    (Accepted Answer Satisfies This Scenario Only)

Updated: If you see file "1.html" on plunker. I am trying to set
<my-title> First page</my-title>
. but that is not working. My key idea is that developer will give
<my-title>Current Page Title</my-title>
on partial and it will be shown as per current page when he navigates across.

Please keep in mind I will be exposing only
to partial and controller.
will be at one place only. Only Title will be changed.
If there are some new pages navigation links will be added to

There is lot of code to copy-paste here. Please visit this PLUNKER.

module.component('myFirstApp', {
templateUrl: "mainview.html",
$routeConfig: [
{path: '/', redirectTo: ['/First'] },
{path: '/first', name: 'First', component: 'firstComponent'},
{path: '/second', name: 'Second', component: 'secondComponent'}

module.component('firstComponent', {
templateUrl: "1.html"

module.component('secondComponent', {
templateUrl: "2.html"

module.component('myTitle', {
template: '<h1>{{model.title}}</h1>'

module.component('myHeader', {
templateUrl: "my-header.html"

enter image description here

Answer Source

To me, using component routing, it looks like a good idea to use a controller for handling your title. (with ui-router, I would have used the resolve option).

I decided to inject $rootScope, and use it for sharing title value. You can also do it with a service.

so, the component :

module.component('firstComponent', {
  templateUrl: "1.html",
  controller: ["$rootScope", function($rootScope){
    $rootScope.appVars = $rootScope.appVars || {};
    $rootScope.appVars.title = "Title from Page 1";

and the directive :

module.component('myTitle', {
  template: '<h1>{{$root.appVars.title}}</h1>'

Here is your updated plnkr :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download