【发布时间】:2016-05-11 17:24:21
【问题描述】:
问题
我目前正在尝试找出一种方法来在 $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
]
再一次,这行得通;但是,例如,如果 routeScope 上的 person 和 age 属性(在 /person/:id 路由的情况下)仅在 AJAX 调用之后设置,我会得到一个空字符串作为它们的值。
有没有办法实现我正在寻找的东西?我真的很想动态设置<title></title>元素的模板,以及当路由改变时告诉它它的范围是routeScope。
提前致谢。
【问题讨论】:
标签: javascript angularjs ajax coffeescript