如何动态更改基于AngularJS局部视图的标题?
我正在使用ng-view来包含AngularJS部分视图,并且我想根据包含的视图更新页面标题和h1标题标记。 这些超出了局部视图控制器的范围,因此我无法弄清楚如何将它们绑定到控制器中的数据集。
如果是ASP.NET MVC,你可以使用@ViewBag来做到这一点,但我不知道AngularJS中的等价物。 我已经搜索了共享服务,事件等,但仍然无法正常工作。 任何方式来修改我的例子,所以它的作品将不胜感激。
我的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>
我的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"; }
  您可以在<html>级别定义控制器。 
 <html ng-app="app" ng-controller="titleCtrl">
   <head>
     <title>{{ Page.title() }}</title>
 ...
  您创建服务: Page并从控制器修改。 
myModule.factory('Page', function() {
   var title = 'default';
   return {
     title: function() { return title; },
     setTitle: function(newTitle) { title = newTitle }
   };
});
  从控制器注入Page并调用'Page.setTitle()'。 
这里是一个具体的例子:http://plnkr.co/edit/0e7T6l
如果您使用路由,我刚刚发现了一个设置页面标题的好方法:
JavaScript的:
var myApp = angular.module('myApp', ['ngResource'])
myApp.config(
    ['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
            title: 'Home',
            templateUrl: '/Assets/Views/Home.html',
            controller: 'HomeController'
        });
        $routeProvider.when('/Product/:id', {
            title: 'Product',
            templateUrl: '/Assets/Views/Product.html',
            controller: 'ProductController'
        });
    }]);
myApp.run(['$rootScope', function($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);
HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title ng-bind="'myApp — ' + title">myApp</title>
...
  编辑 :使用ng-bind属性而不是curlies {{}}以便它们在加载时不显示 
请注意,您也可以直接使用javascript设置标题,即,
$window.document.title = someTitleYouCreated;
  这没有数据绑定,但将<html> ng-app <html> ng-app放入<html>标记时有问题。  (例如,使用JSP模板,其中<head>仅在一个位置定义,但您有多个应用程序。) 
上一篇: How to dynamically change header based on AngularJS partial view?
