javascript - How to dynamically change header based on AngularJS partial view? -
i using ng-view include angularjs partial views, , want update page title , h1 header tags based on included view. these out of scope of partial view controllers though, , can't figure out how bind them data set in controllers.
if asp.net mvc use @viewbag this, don't know equivalent in angularjs. i've searched shared services, events etc still can't working. way modify example works 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 put in title , h1 */ } function test2ctrl($scope, $http) { $scope.header = "test 2"; }
you define controller @ <html>
level.
<html ng-app="app" ng-controller="titlectrl"> <head> <title>{{ page.title() }}</title> ...
you create service: page
, modify controllers.
mymodule.factory('page', function() { var title = 'default'; return { title: function() { return title; }, settitle: function(newtitle) { title = newtitle } }; });
inject page
, call 'page.settitle()' controllers.
here concrete example: http://plnkr.co/edit/0e7t6l
Comments
Post a Comment