UI-Router를 사용하여 페이지 제목 설정
Angular를 마이그레이션합니다.내장된 라우팅 대신 UI 라우터를 사용하는 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' }
})
});
pageTitle 변수를 사용하여 페이지 제목을 동적으로 설정하려면 어떻게 해야 합니까?빌트인 루팅을 사용하여
$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
$rootScope.pageTitle = $route.current.data.pageTitle;
});
아래 그림과 같이 변수를 HTML로 바인드합니다.
<title ng-bind="$root.pageTitle"></title>
UI 라우터를 사용하여 연결할 수 있는 유사한 이벤트가 있습니까?'onEnter'와 'onExit' 함수가 있는 것을 알 수 있었습니다만, 그것들은 각 상태에 관련되어 있는 것 같기 때문에 $rootScope 변수를 설정하기 위해 코드를 반복해야 합니다.
Use 사용하다$stateChangeSuccess
.
지시문에 넣을 수 있습니다.
app.directive('updateTitle', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
return {
link: function(scope, element) {
var listener = function(event, toState) {
var title = 'Default Title';
if (toState.data && toState.data.pageTitle) title = toState.data.pageTitle;
$timeout(function() {
element.text(title);
}, 0, false);
};
$rootScope.$on('$stateChangeSuccess', listener);
}
};
}
]);
그리고:
<title update-title></title>
데모: http://run.plnkr.co/8tqvzlCw62Tl7t4j/ #/home
코드: http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview
와 께 도 even with함라$stateChangeSuccess
그 the$timeout
내가 직접 시험했을 때 적어도 내가 시험했을 때 적어도 내가 시험을 치렀다.적어도 내 자신을 시험해봤을 때 정확한 역사를 위해 필요했던 거야
편집: 2014년 11월 24일 - 선언적 접근법:
app.directive('title', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
return {
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);
}
};
}
]);
그리고:
<title>{{title}}</title>
데모: http://run.plnkr.co/d4s3qBikieq8egX7/#/http://http:/http://run.plnkr.co/d4s3qBikieq8egX7/
코드: http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview
여기에 있는 대부분의 답을 조합함으로써 이를 수행하는 또 다른 방법이 있습니다.이미 답변한 내용이지만 UI 라우터를 사용하여 동적으로 페이지 제목을 변경하는 방법을 보여드리고 싶었습니다.
ui-router 샘플앱을 보면 Angular .run 블록을 사용하여 $state 변수를 $rootScope에 추가합니다.
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.
// For example, <li ng-class="{ active: $state.includes('contacts.list') }">
// will set the <li> to active whenever 'contacts.list' or one of its
// decendents is active.
.run([ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
이렇게 정의하면 페이지 제목을 투고했지만 정의된 상태를 사용하도록 수정한 내용으로 쉽게 동적으로 업데이트할 수 있습니다.
같은 방법으로 상태를 설정합니다.
.state('home', {
url: '/home',
templateUrl : 'views/home.html',
data : { pageTitle: 'Home' }
})
html을 조금 편집해서...
<title ng-bind="$state.current.data.pageTitle"></title>
지금까지의 답변보다 낫다고는 말할 수 없지만, 이해하고 실천하는 것이 더 쉬웠습니다.
angular-ui-router-title 플러그인을 사용하면 페이지 제목을 현재 상태에 따라 정적 또는 동적 값으로 쉽게 업데이트할 수 있습니다.브라우저 이력에서도 올바르게 동작합니다.
$stateChangeSuccess
는 UI-Router 1.x에서 폐지되어 디폴트로 디세블로 되어 있습니다.이제 새로운 버전을 사용해야 합니다.$transition
서비스.서비스.
해야 하는지 않습니다.$transition
@troig 님의 도움을 받아서 모든 것을 이해했습니다.제목 업데이트를 위해 생각해낸 내용은 다음과 같습니다.
이것을 Angular 1.6 어플리케이션에 넣습니다.ECMAScript 6 구문을 사용하고 있습니다.구문을 사용하고 있지 않은 경우는 로 변경해야 합니다.
.run(function($transitions, $window) {
$transitions.onSuccess({}, (transition) => {
let title = transition.to().title;
if (title) {
if (title instanceof Function) {
title = title.call(transition.to(), transition.params());
}
$window.document.title = title;
}
});
그냥 'a'를 돼요.title
state string to your state:
$stateProvider.state({
name: "foo",
url: "/foo",
template: "<foo-widget layout='row'/>",
title: "Foo Page""
});
그러면 제목에 "Foo Page"라는 단어가 나타납니다.(주제목이 없는 경우 페이지 제목은 갱신되지 않습니다.상태가 디폴트 타이틀을 지정하지 않는 경우는, 상기의 코드를 갱신해 디폴트 타이틀을 지정하는 것은 간단합니다).
에서는 '아까보다'의 도 있습니다.title
. 。this
함수 호출에 사용되는 것은 상태 자체이며, 다음 예시와 같이1개의 인수는 상태 파라미터가 됩니다.
$stateProvider.state({
name: "bar",
url: "/bar/{code}",
template: "<bar-widget code='{{code}}' layout='row'/>",
title: function(params) {
return `Bar Code ${params.code}`;
}
});
경로 URL " " " 。/bar/code/123
페이지 제목으로 "바코드 123"이 표시됩니다.ECMAScript 6 구문을 사용하여 문자열을 포맷하고 추출합니다.
시간이 있는 사람이 이런 것을 지시문에 넣어 모두가 사용할 수 있도록 발행해 주었으면 합니다.
$rootscope에 $state를 첨부하여 앱 내 어디에서나 사용할 수 있습니다.
app.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
<title ng-bind="$state.current.name + ' - ui-router'">about - ui-router</title>
.state('app.staff.client', {
url: '/client/mine',
title: 'My Clients'})
그리고 제 HTML에는 다음과 같은 내용이 있습니다.
<h3>{{ $state.current.title }}</h3>
window.document.title만 업데이트하면 됩니다.
.state('login', {
url: '/login',
templateUrl: "/Login",
controller: "loginCtrl",
onEnter: function($window){$window.document.title = "App Login"; }
})
이렇게 하면 'ng-app'은 HTML 태그로 이동할 필요가 없고 본문이나 아래쪽에 머물 수 있습니다.
페이지 제목 설정뿐만 아니라 설명에도 잘 맞는 ngMeta를 사용하고 있습니다.각 상태의 특정 제목/설명, 제목/설명 미지정 시 기본값 및 기본 제목 접미사(' | MySiteName' 등) 및 작성자 값을 설정할 수 있습니다.
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home.html',
controller: 'HomeController',
meta: {
'title': 'Home',
'titleSuffix': ' | MySiteName',
'description': 'This is my home page description lorem ipsum.'
},
})
당신은 사실 첫 번째 대답/질문에 매우 근접해 있습니다.제목을 데이터 개체로 추가합니다.
.state('home', {
url: '/home',
templateUrl : 'views/home.html',
data : { pageTitle: 'Home' }
})
index.html에서 데이터를 페이지 제목에 직접 바인드합니다.
<title data-ng-bind="$state.current.data.pageTitle + ' - Optional text'">Failsafe text</title>
결국 마틴이랑 타세카 조합이 나왔는데TT의 답변 - 단순하고 템플릿과 관련된 내용이 없습니다.
$rootScope.$on("$stateChangeSuccess", function (event, toState) {
$timeout(function () { // Needed to ensure the title is changed *after* the url so that history entries are correct.
$window.document.title = toState.name;
});
});
왜 그냥 안 돼?
$window.document.title = 'Title';
업데이트: 전체 지시 코드
var DIRECTIVE = 'yourPageTitle';
yourPageTitle.$inject = ['$window'];
function yourPageTitle($window: ng.IWindowService): ng.IDirective {
return {
link: (scope, element, attrs) => {
attrs.$observe(DIRECTIVE, (value: string) => {
$window.document.title = value;
});
}
}
}
directive(DIRECTIVE, yourPageTitle);
그 후 모든 페이지에 다음 지시문을 포함합니다.
<section
your-page-title="{{'somePage' | translate}}">
ES6 를 사용하고 있는 경우는, 이 조작은 정상적으로 동작합니다.
class PageTitle {
constructor($compile, $timeout) {
this.restrict = 'A';
this._$compile = $compile;
this.$timeout = $timeout;
}
compile(element) {
return this.link.bind(this);
}
link(scope, element, attrs, controller) {
let defaultTitle = attrs.pageTitle ? attrs.pageTitle : "My Awesome Sauce Site";
let listener = function(event, toState) {
let title = defaultTitle;
if (toState.data && toState.data.title) title = toState.data.title + ' | ' + title;
$('html head title').text(title);
};
scope.$on('$stateChangeStart', listener);
}
}
export function directiveFactory($compile) {
return new PageTitle($compile);
}
directiveFactory.injections = ['$compile', '$timeout'];
export default PageTitle;
이 지시문을 써보세요.
https://github.com/afeiship/angular-dynamic-title
다음은 예를 제시하겠습니다.
html:
<title dynamic-title>Title</title>
<a href="javascript:;" ui-sref="state1">State1 page</a>
<a href="javascript:;" ui-sref="state2">State2 page</a>
javascript:
var TestModule = angular.module('TestApp', ['ui.router','nx.widget'])
.config(function ($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html",
data:{
pageTitle:'State1 page title11111'
}
})
.state('state2', {
url: "/state2",
templateUrl: "partials/state2.html",data:{
pageTitle:'State2 page title222222'
}
});
})
.controller('MainCtrl', function ($scope) {
console.log('initial ctrl!');
});
업데이트된 UI-Router 1.0.0 이상 버전의 경우 https://ui-router.github.io/guide/ng1/migrate-to-1_0)
다음 코드를 참조하십시오.
app.directive('pageTitle', [
'$rootScope',
'$timeout',
'$transitions',
function($rootScope, $timeout,$transitions) {
return {
restrict: 'A',
link: function() {
var listener = function($transitions) {
var default_title = "DEFAULT_TITLE";
$timeout(function() {
$rootScope.page_title = ($transitions.$to().data && $transitions.$to().data.pageTitle)
? default_title + ' - ' + $transitions.$to().data.pageTitle : default_title;
});
};
$transitions.onSuccess({ }, listener);
}
}
}
])
다음 항목을 index.html에 추가합니다.
<title page-title ng-bind="page_title"></title>
언급URL : https://stackoverflow.com/questions/23813599/set-page-title-using-ui-router
'programing' 카테고리의 다른 글
Wordpress 외부 구텐베르크 에디터 (0) | 2023.03.23 |
---|---|
jQuery UI 자동 완성:제안된 리스트에서 선택한 값만 허용 (0) | 2023.03.18 |
isPresent 메서드와 isDisplayed 메서드의 차이점은 무엇입니까? (0) | 2023.03.18 |
상속된 개체를 JSON으로 문자열화하는 방법 (0) | 2023.03.18 |
모든 http 콜에서 디폴트 요구 헤더의 액시오 설정을 작성하려면 어떻게 해야 합니까? (0) | 2023.03.18 |