問題
我目前試圖找出一種方法來動態地改變0模板時$route
變化動態標題。我已經看到了各種解決方案,其中包括$broadcast
消息或傳遞工廠到setTitle
或這樣的事情。我想如果我可以簡單地在我的$routeProvider
級別上定義這一點,但也允許它足夠靈活以在當前範圍$route
上使用變量。AngularJS - 用插值
我有什麼
目前我有一個使用$interpolate
達到我想要的東西有點可行的解決方案;問題是,例如,如果該屬性是在AJAX調用之後設置的,則該模板不會更新。
routes.coffee
angular.module('app').config ['$routeProvider', ($routeProvider) ->
$routeProvider
.when '/',
templateUrl: 'templates/home.html'
controller: 'Home'
.when '/person/:id'
templateUrl: 'templates/person.html'
controller: 'Person'
title: '{{name}} ({{age}})'
]
lwTitle.coffee
angular.module('app').directive 'lwTitle', ['$route', '$interpolate', ($route, $interpolate) ->
link: (scope, el) ->
whenRouteScopeChanges = -> $route.current?.scope
updateTitle = (routeScope) ->
if routeScope
title = $route.current?.$$route.title or 'Home'
el.html $interpolate("#{title} - My App")(routeScope)
scope.$watch whenRouteScopeChanges, updateTitle
]
同樣,該工程;但是,例如,如果僅在AJAX調用後設置routeScope
上的person
和age
屬性(在/person/:id
路由的情況下),則會爲其值創建一個空字符串。
有沒有辦法實現我在找的東西?我真的想動態地設置<title></title>
元素的模板,並且告訴它當路由改變時它的範圍是routeScope
。
在此先感謝。
感謝有關'resolve'尖端。我確實喜歡這種方法,因爲我常常會依賴於承諾的成功,這樣用戶在解決問題之前不會進入頁面。 – Levi
我_still_想知道是否有辦法做我想做的事情,我可以''編譯'模板或東西到我的'el'中,並把'$ scope'放在當前路由的上下文中。 我稍等一下,看看有沒有辦法做到這一點,但我可能會接受這個答案。再次感謝 :) – Levi