繁体   English   中英

如何使用Angular 1.5中的组件为每个页面设置标题

[英]how to set header for each page using component in Angular 1.5

我最近开始使用Angular 1.5组件。 我的申请表中有各种页面。 所以我决定创建一个在<my-header>组件中使用的<my-title> <my-header>组件。 正如您在导航栏中看到的,我有First,Second作为导航链接。 在我的应用程序中,将有更多的父子组合。

我想通过两种方式设置每个页面的标题。

  1. 通过部分<my-title>Home</my-title> (参见1.html或2.html)(Manuel的答案满足此场景)
  2. 我也想从控制器设置它。 vm.title = "current page title" (已接受的答案仅满足此方案)

我认为任何一件事都可以从以上两个选项中完成。 不同的人对选项1(Deblaton)和选项2(Manuel)有两个答案。 两个答案都满足各自的情景。 我接受了谁先正确回答。

更新:如果您在plunker上看到文件“1.html”。 我正在尝试设置<my-title> First page</my-title> 但那不起作用。 我的主要想法是开发人员将部分地给出<my-title>Current Page Title</my-title> ,并且当他导航时将按当前页面显示。

请记住,我只会将<my-title>暴露给部分和控制器。 <my-header>仅限于一个地方。 只有标题会被更改。 如果有一些新页面,导航链接将添加到<my-header>

这里有很多代码可以复制粘贴。 请访问这个PLUNKER

module.component('myFirstApp', {
   templateUrl: "mainview.html",
   $routeConfig: [
     {path: '/', redirectTo: ['/First'] },
     {path: '/first', name: 'First', component: 'firstComponent'},
     {path: '/second', name: 'Second', component: 'secondComponent'}
   ]
 })

 module.component('firstComponent', {
   templateUrl: "1.html"
 });

 module.component('secondComponent', {
   templateUrl: "2.html"
 });

 module.component('myTitle', {
   template: '<h1>{{model.title}}</h1>'
 });

 module.component('myHeader', {
   templateUrl: "my-header.html"
 });

在此输入图像描述

对我来说,使用组件路由,使用控制器处理标题似乎是个好主意。 (使用ui-router,我会使用resolve选项)。

我决定注入$ rootScope,并用它来共享标题值。 您也可以使用服务。

所以,组件:

module.component('firstComponent', {
  templateUrl: "1.html",
  controller: ["$rootScope", function($rootScope){
    $rootScope.appVars = $rootScope.appVars || {};
    $rootScope.appVars.title = "Title from Page 1";
  }]
});

和指令:

module.component('myTitle', {
  template: '<h1>{{$root.appVars.title}}</h1>'
});

这是您更新的plnkr: https ://plnkr.co/edit/6PCfznxsJzCPQtBm2oyN p = preview

您在代码中遗漏了一些东西。

  1. 您需要使用绑定才能将参数传递给组件
  2. 您在模板中使用“模型”一词来指代模型,但这不是默认设置。 在这里你可以做两件事,你可以在模板中使用$ ctrl或在组件中定义controllerAs。

组件示例:

module.component('myTitle', {
  template: '<h1>{{model.title}}</h1>',
  controllerAs: 'model',
  bindings: {
    title: '<'
  }
});

使用示例:

<my-title title="'I am First'"></my-title>

请注意“'我是第一个'”中双引号内的引号。 你需要两个,因为你传递一个字符串作为参数。

为了更改标题中的标题,我创建了一个服务,允许来自ng-outlet和外部组件下的组件进行通信,因为您无法通过路由将数据作为绑定传递。

您的Plunker包含更改: https ://plnkr.co/edit/ScpJYQItsMQlyd1Eacyi?p = preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM