![](/img/trans.png)
[英]How to set scope to false with Angular 1.5 component() method
[英]how to set header for each page using component in Angular 1.5
我最近開始使用Angular 1.5組件。 我的申請表中有各種頁面。 所以我決定創建一個在<my-header>
組件中使用的<my-title>
<my-header>
組件。 正如您在導航欄中看到的,我有First,Second作為導航鏈接。 在我的應用程序中,將有更多的父子組合。
我想通過兩種方式設置每個頁面的標題。
<my-title>Home</my-title>
(參見1.html或2.html)(Manuel的答案滿足此場景) 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
您在代碼中遺漏了一些東西。
組件示例:
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.