2014-09-10 63 views
0

我有一個使用Ui路由器進行路由的Angular應用程序。每次我更改路由器時,我都想更改頁面的標題,並且好像$ stateProvider是最簡單的方法。我有這樣的事情爲$ stateProvider:Angular UI路由器設置範圍/變量

$stateProvider 
    .state('index', { 
     url: "/", 
     views: { 
      "rightContainer": { templateUrl: "viewA.html" }, 
     }, 
     controller: function ($scope) { 
      $scope.data.header = "Header 1" 
     } 
    }) 
    .state('details', { 
     url: "/details", 
     views: { 
      "rightContainer": { templateUrl: "ViewB.html" }, 
     }, 
     controller: function ($scope) { 
      $scope.data.header = "Header 2" 
     } 
    }); 

那麼我想有頭:

<div data-ng-controller="mainCtrl"> 
       <div class='bg'>{{data.header}}</div> 
    </div> 
+0

可能,最好採用DA ta https://github.com/angular-ui/ui-router/wiki#attach-custom-data-to-state-objects – Whisher 2014-09-10 18:31:49

回答

1

您可以使用數據https://github.com/angular-ui/ui-router/wiki#attach-custom-data-to-state-objects 或只是另一種方法

.run(function ($state,$rootScope$filter,WindowUtils) { 
     $rootScope.$state = $state; 
     $rootScope.$on('$stateChangeSuccess', function(event, toState) { 
      var stateName = toState.name; 
      //switch 
      WindowUtils.setTitle(stateName); 
     }); 
    }) 
    .factory('WindowUtils', function($window) { 
     return { 
      setTitle:function(title){ 
       var sep = ' - '; 
       var current = $window.document.title.split(sep)[0]; 
       $window.document.title = current + sep + title; 
      } 
     }; 
    }) 
1

.state對象有一個data屬性,正是你想要實現的。只需添加data: {header: "Header 1"}即可。 state像這樣:

$stateProvider 
.state('index', { 
    url: "/", 
    views: { 
     "rightContainer": { templateUrl: "viewA.html" }, 
    }, 
    data: {header: "Header 1"} 
}) 

編輯/更新

要訪問data的頁面標題等,其如果你使用的index.html <head>一個controller,並使用$scope.$on對推動更改爲$scope.header最好路線變更事件。我建議看看https://github.com/ngbp/ngbp項目樣板作爲一個工作示例。

HTML

https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/index.html

<html ng-app="myApp" ng-controller="AppCtrl"> 
    <head> 
     <title ng-bind="header"></title> 
     ... 
    </head> 

app.js

https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/app/app.js

.controller('AppCtrl', function AppCtrl ($scope, $location) { 
    $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ 
    if (angular.isDefined(toState.data.header)) { 
     $scope.header = toState.data.header; 
    } 
}); 
+0

這似乎是要走的路,但我該如何訪問它。按照文檔提示的方式進行操作無效。 .controller(「mainCtrl」,function($ scope,$ state){ var header = $ state.current.data.header; } – KJ3 2014-09-14 00:31:53

+2

請看這裏的答案:http://stackoverflow.com/questions/ 26922451/angular-ui-router-variable-in-nested-view換句話說,你可以通過向控制器添加$ state作爲參數來獲取它,然後通過$ state.current.data.header來訪問它 – 2014-12-08 10:18:21