How to dynamically change header based on AngularJS partial view?

后端 未结 22 2300
一向
一向 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:24

    Custom Event Based solution inspired from Michael Bromley

    I wasn't able to make it work with $scope, so I tried with rootScope, maybe a bit more dirty... (especially if you make a refresh on the page that do not register the event)

    But I really like the idea of how things are loosely coupled.

    I'm using angularjs 1.6.9

    index.run.js

    angular
    .module('myApp')
    .run(runBlock);
    
    function runBlock($rootScope, ...)
    {
      $rootScope.$on('title-updated', function(event, newTitle) {
        $rootScope.pageTitle = 'MyApp | ' + newTitle;
      });
    }
    

    anyController.controller.js

    angular
    .module('myApp')
    .controller('MainController', MainController);
    
    function MainController($rootScope, ...)
    {
      //simple way :
      $rootScope.$emit('title-updated', 'my new title');
    
      // with data from rest call
      TroncQueteurResource.get({id:tronc_queteur_id}).$promise.then(function(tronc_queteur){
      vm.current.tronc_queteur = tronc_queteur;
    
      $rootScope.$emit('title-updated', moment().format('YYYY-MM-DD') + ' - Tronc '+vm.current.tronc_queteur.id+' - ' +
                                                 vm.current.tronc_queteur.point_quete.name + ' - '+
                                                 vm.current.tronc_queteur.queteur.first_name +' '+vm.current.tronc_queteur.queteur.last_name
      );
     });
    
     ....}
    

    index.html

    
    
      
        
        My App
    

    It's working for me :)


提交回复
热议问题