controller.js
angular.module('myApp', [ ] )</span> .run(['$location','$rootScope',function($location, $rootScope){ $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { $rootScope.title = toState.title }); }]);
router.js
$stateProvider .state('global.search', { title: ' 這裡設定每個page的title', url: '/global/search?q&company&user®ion&account_type&call_type®istered', views: { 'main': { templateUrl: helper.getUrl('global.search'), controller: 'searchCtrl', } } })
index.html
<!doctype html><html lang="zh-cmn-Hans" ng-app="myApp"><head> <meta charset="UTF-8"> <title ng-bind="title">這裡是預設的標題啦</title></head><body> <div ui-view></div></body></html>
通過ng-bind指令將 $rootScope下的title綁定到html頁面中
在$stateProvide.state中設定一個屬性用力傳遞title內容,這裡設定的是title屬性
在首頁的angualr.module()下運行run()函數用來擷取router傳來的title屬性,每當網頁更改跳轉就會觸發$stateChangeSuccess事件
這裡的$stateChangeSuccess事件不可以用$routechangesuccess事件替代,如果不用ui-router外掛程式則可以,代碼如下:
router.js
.config(function($stateProvider, $urlRouterProvider) {$urlRouterProvider.otherwise('/home');$stateProvider .state('home', { url: '/home', templateUrl : 'views/home.html', data : { pageTitle: 'Home' } }) .state('about', { url: '/about', templateUrl : 'views/about.html', data : { pageTitle: 'About' } }) });
controller.js
$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){ $rootScope.pageTitle = $route.current.data.pageTitle; });
index.html
<title ng-bind="<span style="font-family: Arial, Helvetica, sans-serif;">pageTitle</span>"></title>