[英]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.