问题
我目前正在尝试找出一种动态更改 <title></title>
的方法$route
时的模板变化。我已经看到了执行此操作的各种解决方案,其中涉及 $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
]
同样,这有效;但是,例如,如果 person
和 age
routeScope
上的属性(在 /person/:id
路由的情况下)仅在 AJAX 调用后设置,我得到一个空字符串作为它们的值。
有没有办法实现我正在寻找的东西?我真的很想设置 <title></title>
元素的动态模板,以及告诉它它的范围是routeScope
当路线改变时。
提前致谢。
最佳答案
你应该使用 resolve property在您的路线上 - 然后首先您的 ajax 调用将检索数据,然后将填充路线。
route.resolve - An optional map of dependencies which should be injected into the controller.
它看起来像这样
//normal javascript
$routeProvider.when('/', {
templateUrl: 'templates/home.html'
resolve:{
promiseObject: function($http){
return $http({method: 'GET', url: '/someUrl'})
.then (function (data) {
return doSomeStuffFirst(data);
});
}
}});
关于javascript - AngularJS - 带插值的动态标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161383/