How to dynamically change header based on AngularJS partial view?

后端 未结 22 2364
一向
一向 2020-11-22 10:53

I am using ng-view to include AngularJS partial views, and I want to update the page title and h1 header tags based on the included view. These are out of scope of the parti

22条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 11:28

    The module angularjs-viewhead shows a mechanism to set the title on a per-view basis using only a custom directive.

    It can either be applied to an existing view element whose content is already the view title:

    About This Site

    ...or it can be used as a standalone element, in which case the element will be invisible in the rendered document and will only be used to set the view title:

    About This Site
    

    The content of this directive is made available in the root scope as viewTitle, so it can be used on the title element just like any other variable:

    My Site
    

    It can also be used in any other spot that can "see" the root scope. For example:

    {{viewTitle}}

    This solution allows the title to be set via the same mechanism that is used to control the rest of the presentation: AngularJS templates. This avoids the need to clutter controllers with this presentational logic. The controller needs to make available any data that will be used to inform the title, but the template makes the final determination on how to present it, and can use expression interpolation and filters to bind to scope data as normal.

    (Disclaimer: I am the author of this module, but I'm referencing it here only in the hope that it will help someone else to solve this problem.)

提交回复
热议问题