programing

각도로 페이지 제목을 설정하는 방법JS

showcode 2023. 3. 6. 21:40
반응형

각도로 페이지 제목을 설정하는 방법JS

각 Angular의 페이지 제목을 표시하려면 다음 코드를 사용합니다.JS 앱템플릿인데 테스트하기 위해 잘못된 URL을 입력하려고 할 때마다 다음 오류가 나타납니다.

TypeError: Cannot read property 'title' of undefined
    at http://localhost/app/js/app.js:34:43

다음은 사용된 app.js, index.html 코드입니다.

app.js:

var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {

       $routeProvider.when('/home', 
                {     templateUrl: 'templates/index.html', 
                      controller: 'MainController',
                      title: 'Welcome to Home Page'
                });
        $routeProvider.otherwise({
                                    redirectTo: '/home'

                                 });

}]);


myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

Index.html:

<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>

제안해 주세요

$routeChangeSuccess어떤 경우에도 이벤트가 트리거되므로 루트의 존재를 테스트하여 오류를 회피하십시오.

myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {

        if (current.hasOwnProperty('$$route')) {

            $rootScope.title = current.$$route.title;
        }
    });
}]);

언급URL : https://stackoverflow.com/questions/22326307/how-to-set-page-title-with-angularjs

반응형