How to bind data in title element using angular.js

后端 未结 5 1067
走了就别回头了
走了就别回头了 2021-01-02 05:46

I\'m learning Angular.js and I set {{title}} and I try to change that using select element


                        
    
提交评论

  • 2021-01-02 06:22

    When dealing with the title tag you should use ng-bind-template so you don't see the expression in its raw state {{someVar}} before Angular has a chance to kick in. You can add the initial text of the title within the title tag and it will be overwritten by your template.

    <html data-ng-app="app">
      <head>
        <title ng-bind-template="My App - {{title}}">My App - Default Title</title>
      </head>
      <body>
        {{title}}
        <select ng-model="title">
          <option value="Lorem">Lorem</option>
          <option value="Ipsum">Ipsum</option>
          <option value="Dolor">Dolor</option>
        </select>
      </body>
    </html>
    
    0 讨论(0)
  • 2021-01-02 06:24

    Use $rootScope

    .when('/', {
       templateUrl: '/templates/page/home.html',
       controller: ['$scope','$rootScope', function ($scope,$rootScope) {
          $rootScope.title = 'Учитель24.рф';
     }]});
    
    0 讨论(0)
  • 2021-01-02 06:27

    I figured out one solution to set title in <title> tag.

    main.js :

    app = angular.module('myApp', ['ngRoute']);
    app.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
          when("/faq", {
          controller: "MYCtrl",
          templateUrl: "../assets/templates/faq.html",
          title: "FAQ"
        });  
    
    }]);
    
    
    app.run(['$location', '$rootScope', function( $location, $rootScope ){
      $rootScope.$on("$routeChangeSuccess", function(event, currentRoute, previousRoute) {
        $rootScope.title = currentRoute.title;
      });
    }]);
    

    application.html.erb:

    <title ng-bind="'MYAPP - ' + $root.title"></title>

    0 讨论(0)
  • 2021-01-02 06:41

    Since @madhead gave you an awesome answer, I just want to shed some light on your question about why your code doesn't work.

    You can definitely use ng-change, please take a look at this code. Your approach is very close, and I guess maybe you missed something?

    <ul ng-app="myapp" ng-controller="MainCtrl">
        <div>{{title}}</div>
        <select ng-model="user.title" ng-change="set()">
            <option value="Lorem">Lorem</option>
            <option value="Ipsum">Ipsum</option>
            <option value="Dolor">Dolor</option>
        </select>
    </ul>
    
    function MainCtrl($scope) {
        $scope.set = function () {
            $scope.title = $scope.user.title;
        };
    }
    

    I want to point out one thing. If you test in jsfiddle, don't use <title>{{title}}</title>, use <div>{{title}}</div> instead. Somehow title tag will not show correctly in the demo window.

    Demo

    0 讨论(0)
  • 提交回复
    热议问题