angularjs 中通過ui-router設定不同網頁不同內容
阿新 • • 發佈:2019-01-11
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>