簡體   English   中英

AngularJS - 帶插值的動態標題

[英]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上的personage屬性(在/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM