2017-09-25 42 views
0

以下指令被提供当前路线值无法更新角1个应用程序的标题上路由改变

(function() { 
    var titleDirective=angular.module('titleDirective',[]); 
    titleDirective.directive('testTitle',function ($rootScope, $timeout) { 
     return { 
      restrict: 'E', 
      link: function() { 
       var listener = function(event, toState) { 
        $timeout(function() { 
         $rootScope.title = (toState.data && toState.data.pageTitle) 
          ? toState.data.pageTitle 
          : 'Default title'; 
        }); 
       }; 
       $rootScope.$on('$stateChangeSuccess', listener); 
      } 
     }; 
    }) 
})(); 

和我有限定的路由如下所示

.state('admin.signIn', { 
      url: '/signIn', 
      templateUrl: 'credentials/signIn.html', 
      controller: 'loginCtrl', 
      data : { pageTitle: 'Home' } 
     }) 

当我尝试使用下面的index.html中所示的指令

<test-title>{{title}}</test-title> 

但不知道如何更新val UE在改变HTML路由的标题标签

<title>Retailer Application</title> 

不知道如何使用{{title}}的表现之类的标题

请提出一个办法做到这一点

回答

1

更新你的指令:

myApp.directive('testTitle', function($rootScope, $timeout) { 
    return { 
    restrict: 'E', 
    template: `<title>{{$root.title}}</title>`, 
    link: function() { 
     var listener = function(event, toState) { 
     $timeout(function() { 
      $rootScope.title = (toState.data && toState.data.pageTitle) ? toState.data.pageTitle : 'Default title'; 
     }); 
     }; 
     $rootScope.$on('$stateChangeSuccess', listener); 
    } 
    }; 
}); 

这里,只要您使用模板中的$ rootScope为标题变量,你已经使用{{$root.title}}。之后,仅仅在index.html的

Working Plunker

头部分添加test-title指令还请确保您使用的是0.4.2版本UI的路由器。使用ui-router $ stateChangeSuccess事件的最新版本(1.x)已弃用。改为使用$transitions.onSuccess

Official Documentation & issue

+0

plunker例子是惊人 –

相关问题