javascript - 如何根据AngularJS局部 View 动态更改标题?

标签 javascript angularjs templates partial-views angular-routing

我正在使用 ng-view 来包含 AngularJS 部分 View ,并且我想根据包含的 View 更新页面标题和 h1 标题标签。这些超出了部分 View Controller 的范围,所以我不知道如何将它们绑定(bind)到 Controller 中的数据集。

如果是 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"; }

最佳答案

如果您使用路由,我刚刚发现了一种设置页面标题的好方法:

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 &mdash; ' + title">myApp</title>
...

编辑:使用 ng-bind 属性而不是 curlies {{}},因此它们不会在加载时显示

关于javascript - 如何根据AngularJS局部 View 动态更改标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506329/

相关文章:

javascript - Angular js ui-router共享 Controller

javascript - 在特定 url 上关闭 angularjs 中的窗口

javascript - 帮助 CSS + 媒体查询 + 元素样式

javascript - Shadow Dom继承父页面CSS [Chrome]

javascript - jQuery 与 Javascript 点击

javascript - CORS XMLHttpRequest 请求来源和引用者

c++模板问题

c++ - 模板变量

c++ - 指针的函数模板特化

javascript - 如何按键对对象数组进行分组?