[英]AngularJS - Dynamic Title with interpolation
我正在嘗試找出一種在$route
更改時動態更改<title></title>
模板的方法。 我已經看到了這樣做的各種解決方案,涉及$broadcast
消息或者將工廠傳遞給setTitle
或其他類似的東西。 我想如果我可以簡單地在$routeProvider
級別定義它,但也允許它足夠靈活,以便在$route
的當前范圍上使用變量。
目前我有一個有點工作的解決方案,使用$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屬性 - 然后首先您的ajax調用將檢索數據,然后將填充路由。
route.resolve - 應該注入控制器的可選依賴關系映射。
它看起來像這樣
//normal javascript
$routeProvider.when('/', {
templateUrl: 'templates/home.html'
resolve:{
promiseObject: function($http){
return $http({method: 'GET', url: '/someUrl'})
.then (function (data) {
return doSomeStuffFirst(data);
});
}
}});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.