如何基于 AngularJS 局部视图动态更改标题? [英] How to dynamically change header based on AngularJS partial view?

查看:23
本文介绍了如何基于 AngularJS 局部视图动态更改标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ng-view 来包含 AngularJS 部分视图,我想根据包含的视图更新页面标题和 h1 标题标签.但是,这些超出了局部视图控制器的范围,因此我无法弄清楚如何将它们绑定到控制器中的数据集.

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.

如果是 ASP.NET MVC,您可以使用 @ViewBag 来执行此操作,但我不知道 AngularJS 中的等效项.我搜索了共享服务、事件等,但仍然无法正常工作.任何修改我的示例使其有效的方法将不胜感激.

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.

我的 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:

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"; }

推荐答案

您可以在 级别定义控制器.

You could define controller at the <html> level.

 <html ng-app="app" ng-controller="titleCtrl">
   <head>
     <title>{{ Page.title() }}</title>
 ...

您创建服务:Page 并从控制器进行修改.

You create service: Page and modify from controllers.

myModule.factory('Page', function() {
   var title = 'default';
   return {
     title: function() { return title; },
     setTitle: function(newTitle) { title = newTitle }
   };
});

注入 Page 并从控制器调用Page.setTitle()".

Inject Page and Call 'Page.setTitle()' from controllers.

这是具体的例子:http://plnkr.co/edit/0e7T6l

这篇关于如何基于 AngularJS 局部视图动态更改标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆