【问题标题】:AngularJS - Dynamic Title with interpolationAngularJS - 带插值的动态标题
【发布时间】: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 上的 personage 属性(在 /person/:id 路由的情况下)仅在 AJAX 调用之后设置,我会得到一个空字符串作为它们的值。

有没有办法实现我正在寻找的东西?我真的很想动态设置<title></title>元素的模板,以及当路由改变时告诉它它的范围是routeScope

提前致谢。

【问题讨论】:

    标签: javascript angularjs ajax coffeescript


    【解决方案1】:

    您应该在路由上使用resolve property - 然后首先您的 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);
                 });
        }
    }}); 
    

    【讨论】:

    • 感谢您提供有关 resolve 的提示。我确实喜欢这种方法,因为我要使用的控制器通常取决于承诺的成功;这样用户在问题解决之前不会访问该页面。
    • 仍然想知道是否有办法做我想做的事情,我可以在其中将模板 $compile 或其他东西放入我的 el 和不过,将$scope 放在当前路线的上下文中。我会稍等一下,看看是否有任何方法可以做到这一点,但我可能会接受这个答案。再次感谢:)
    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多