角度1:根据当前路线更改标题

时间:2016-03-27 20:13:23

标签: javascript angularjs routing angularjs-routing

如何根据路由器提供的当前控制器更改控制器范围外显示的标题?基本上,我有调用特定路由时加载的mainMenu控制器。但是,在视图之外,存在部分包括的标题。我想根据当前路线更改标题内的输出。我在下面添加了代码结构:

的index.html

<div ng-include="'partials/header.html'"></div>
<div ng-view></div>

/partials/header.html

<header ng-controller="HeaderCtrl">
      <h1>{{ currentTitle }}</h1>
</header>

/partials/main-menu.html

<div ng-controller="MainMenuCtrl">

</div>

路由器

var TaskApp = angular.module('TaskApp', [
  'ngRoute',
  'taskAppControllers'
]);

TaskApp.config(['$routeProvider',
  function($routeProvider){
  $routeProvider.
      when('/main-menu', {
        templateUrl: "partials/main-menu.html",
        controller: "MainMenuCtrl"
      }).
      otherwise({
        redirectTo: "/"
      });
  }]);

控制器:

var taskAppControllers = angular.module('taskAppControllers',[]);

taskAppControllers.controller('TaskAppCtrl',[function(){}]);
taskAppControllers.controller('DesktopCtrl',[function(){}]);

taskAppControllers.controller('MainMenuCtrl', ['$scope','$http',
 function($scope, $http){
  $http.get('data/main-menu.json?' + Math.random()).success(function(data){
    $scope.mainMenuOptions = data;
  });
  $scope.currentTitle = "Main menu"
}]);

taskAppControllers.controller('HeaderCtrl', ['$scope',
 function($scope){
   //
}]);

1 个答案:

答案 0 :(得分:5)

您可以为每个路线选项添加一个属性,类似于title

when('/main-menu', {
    templateUrl: "partials/main-menu.html",
    controller: "MainMenuCtrl",
    title: 'Main Page'
}).

然后在HeaderCtrl内放置$routeChangeSuccess(在路由更改成功时触发)事件,然后抓住当前路由对象并从中获取标题并将其设置为currentTitle范围变量

$scope.$on('$routeChangeSuccess', function(event, current) {
    $scope.currentTitle = current.title;
});