sourcecode

AngularJS에서 메타 태그를 업데이트하려면 어떻게 해야 합니까?

codebag 2023. 3. 14. 21:37
반응형

AngularJS에서 메타 태그를 업데이트하려면 어떻게 해야 합니까?

저는 AngularJS를 사용하여 어플리케이션을 개발하고 있습니다.루트 변경 시 메타 태그를 업데이트하고 싶습니다.
Angular에서 메타 태그를 업데이트하려면 어떻게 해야 합니까?페이지의 "뷰 소스"에 표시할 수 있는 JS?

여기 HTML 코드가 있습니다.

  <!DOCTYPE html>
    <html ng-app="app">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta name="fragment" content="!" />
            <meta name="title" content="Test App">
            <meta name="description" content="Test App">
            <meta name="keywords" content="Test,App">

            <link rel="stylesheet" href="css/jquery-ui-1.10.2.custom.min.css" />
            <link rel="stylesheet" href="css/extra.css" />
            <script src="js/libs/jquery-1.8.3.min.js"></script>
            <script src="js/libs/jquery-ui-1.10.2.custom.min.js"></script>
            <script src="js/libs/angular.min.js"></script>
            <script src="js/controller.js"></script>
            <script src="js/routes.js"></script>
        </head>
        <body>
            <div ng-controller="mainCtrl" class="main-container" loading>
                <div class="container-holder">
                    <div class="container">
                        <div ng-include src='"elements/header.html"'></div>
                        <div ng-view class="clearfix"></div>
                    </div>
                </div>

                <div ng-controller="userCtrl" id="test">
                    <div class="container" class="login-container">
                        <div id="login-logo">
                            <img src="images/logo-300.png" alt="" class="login-img"/>
                            <br />
                            <div ng-view></div>
                        </div>
                    </div>
                </div>
        </body>
    </html>
<html ng-app="app">
    <title ng-bind="metaservice.metaTitle()">Test</title>
    <meta name="description" content="{{ metaservice.metaDescription() }}" />
    <meta name="keywords" content="{{ metaservice.metaKeywords() }}" />


<script>
    var app = angular.module('app',[]);
    app.service('MetaService', function() {
       var title = 'Web App';
       var metaDescription = '';
       var metaKeywords = '';
       return {
          set: function(newTitle, newMetaDescription, newKeywords) {
              metaKeywords = newKeywords;
              metaDescription = newMetaDescription;
              title = newTitle; 
          },
          metaTitle: function(){ return title; },
          metaDescription: function() { return metaDescription; },
          metaKeywords: function() { return metaKeywords; }
       }
    });

   app.controller('myCtrl',function($scope,$rootScope,MetaService){
      $rootScope.metaservice = MetaService;
      $rootScope.metaservice.set("Web App","desc","blah blah");
   });
</script>
 <body ng-controller="myCtrl"></body>


</html>

저는 이 문제를 이틀 전에 서비스를 만들고 $window와 클래식 Javascript를 사용하여 해결했습니다.

html 마크업으로 필요한 메타태그를 만듭니다.(현시점에서는 공백인 채로 두거나 기본값으로 설정할 수 있습니다).

<head> 
    <meta name="title"/>
    <meta name="description"/>
</head>

그럼 그런 서비스를 만들어야겠네요.

angular.module('app').service('MetadataService', ['$window', function($window){
 var self = this;
 self.setMetaTags = function (tagData){
   $window.document.getElementsByName('title')[0].content = tagData.title;
   $window.document.getElementsByName('description')[0].content = tagData.description;
 }; 
}]);

이제 우리는 "자기"를 사용해야 합니다.setMetaTags" 서비스를 컨트롤러 내에서 실행합니다(초기화 시).컨트롤러의 아무 곳에서나 함수를 호출할 수 있습니다.

angular.module('app').controller('TestController', ['MetadataService',function(MetadataService){

   MetadataService.setMetaTags({
       title: 'this',
       description: 'works'
    });

}]);

angular-ui-router를 사용하는 경우 ui-router-metatags를 사용할 수 있습니다.

대부분의 브라우저에서 '원본 보기'를 수행하면 DOM의 JavaScript 조작 전에 서버에서 보낸 문서를 볼 수 있습니다.각진JS 앱은 일반적으로 많은 DOM 조작을 수행하지만 실제로 원본 문서를 변경하지 않습니다.FireFox 또는 Chrome(개발도구 포함)에서 오른쪽 클릭 -> inspect 요소를 실행하면 모든 JavaScript 업데이트가 포함된 렌더링된 DOM이 나타납니다.

따라서 질문에 답하기 위해 변경 내용이 '뷰 소스'에 반영되도록 JavaScript를 사용하여 설명 메타 태그를 업데이트할 방법이 없습니다.그러나 메타 설명 태그를 업데이트하여 브라우저 플러그인(예: 북마크 앱 등)에서 업데이트된 설명을 볼 수 있습니다.그러기 위해서는 다음과 같은 작업을 수행합니다.

var metaDesc = angular.element($rootElement.find('meta[name=description]')[0]);
metaDesc.attr('content', description);

답변을 수정하여 각도에 따라 헤더를 동적으로 변경하는 방법을 찾았습니다.JS 부분 뷰?제 사이트에서 작동하도록 하겠습니다.루트 컨피규레이션에서 메타 콘텐츠를 확립한 후 함수를 에 바인드합니다.$routeChangeSuccessevent를 사용하여 설정된 값을 에 저장합니다.$rootScope메타 태그가 에 바인딩되어 있는 한$rootScope모든 게 계획대로 될 거야

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

angularApp.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/About', {
            templateUrl: 'Features/About/About.html',
            title: 'Here\'s the Title',
            description: 'A Nice Description',
            keywords: 'Some, Keywords, Go, Here'
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');
});

<head>
    <meta charset="utf-8" />
    <meta name="keywords" content="{{keywords}}"/>
    <meta name="description" content="{{description}}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="fragment" content="!" />

    <title ng-bind="title">A Placeholder Title</title>
    <link rel="icon" href="/Images/Logo.ico">
    <base href="/" />
    @Styles.Render("~/Content/css")
</head>

언급URL : https://stackoverflow.com/questions/16119398/how-can-i-update-meta-tags-in-angularjs

반응형