Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Web Technology by (47.6k points)

I am using ng-view to include AngularJS partial views, and I want to update the page title and h1 header tags based on the included view. These are out of scope of the partial view controllers though, and so I can't figure out how to bind them to data set in the controllers.

If it was ASP.NET MVC you could use @ViewBag to do this, but I don't know the equivalent in AngularJS. I've searched about shared services, events etc but still can't get it working. Any way to modify my example so it works would be much appreciated.

My HTML:

<html data-ng-app="myModule">

<head>

<!-- include js files →

<title><!-- should changed when ng-view changes --></title> </head>

<body>

<h1><!-- should changed when ng-view changes --></h1>

<div data-ng-view></div>

</body>

</html>

My JavaScript:

var myModule = angular.module('myModule', []); myModule.config(['$routeProvider', function($routeProvider) { 

  $routeProvider.

when('/test1', {templateUrl: 'test1.html', controller:    Test1Ctrl}).

when('/test2', {templateUrl: 'test2.html', controller: Test2Ctrl}). 

otherwise({redirectTo: '/test1'}); 

}]); 

function Test1Ctrl($scope, $http) { $scope.header = "Test 1"; }

    /* ^ how can I put this in title and h1 */

function Test2Ctrl($scope, $http) { $scope.header = "Test 2"; }

1 Answer

+1 vote
by (106k points)
edited by

If you want to dynamically change header based on AngularJS partial view then you could define controller at the <html> level.

<html ng-app="app" ng-controller="titleCtrl"> 

<head> 

<title>{{ Page.title() }}</title>

</head>

</html>

Are you interested in learning Angularjs from the basics! Here's the right video for you on Angularjs provided by Intellipaat:

You can modify from controllers by creating service: Page see the code below:-

myModule.factory('Page', function() { 

var title = 'default'; 

return { title: function() { return title; }, 

setTitle: function(newTitle) { title = newTitle } 

  }; 

});

Browse Categories

...