【问题标题】:How do I add page-title using angular? [duplicate]如何使用角度添加页面标题? [复制]
【发布时间】:2015-06-03 02:02:29
【问题描述】:

我需要使用 Angular 动态加载页面标题。这样做的最佳方法是什么?任何想法都可能非常有用。

【问题讨论】:

  • 为页面定义一个控制器,并在范围内定义标题

标签: angularjs


【解决方案1】:

如果您在主体级别定义控制器,那将非常容易。如果是这种情况,您可以声明和定义一个范围变量,如 pageTitle 并使用它来显示页面标题。喜欢this

如果不是,并且如果您使用路由来根据路由选择控制器,您仍然可以使用 rootScope 执行此操作,就像它的 shown here 一样。

var myApp = angular.module('myApp', ['ngResource'])

myApp.config(
    ['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
            title: 'Home',
            templateUrl: '/Assets/Views/Home.html',
            controller: 'HomeController'
        });
        $routeProvider.when('/Product/:id', {
            title: 'Product',
            templateUrl: '/Assets/Views/Product.html',
            controller: 'ProductController'
        });
    }]);

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

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title ng-bind="'myApp &mdash; ' + title">myApp</title>

编辑:

This question 在 SO 上的答案非常好,与您正在寻找的类似。

【讨论】:

    【解决方案2】:
     <html ng-app="app" ng-controller="titleCtrl">
       <head>
         <title>{{ title }}</title>
     ...
    

    在你的控制器内部

    app.controller("titleCtrl",function($scope){
         $scope.title="hello page";
    });
    

    不同页面的第二种方式:-

    您可以在级别定义控制器。

     <html ng-app="app" ng-controller="titleCtrl">
       <head>
         <title>{{ Page.title() }}</title>
     ...
    

    您创建服务:从控制器页面和修改。

    app.factory('Page', function() {
       var title = 'default';
       return {
         title: function() { return title; },
         setTitle: function(newTitle) { title = newTitle }
       };
    });
    

    从控制器注入页面并调用“Page.setTitle()”。

    例如:-

    app.controller("pageonectrl",funtion($scope,Page){
    
    Page.setTitle("pageone");
    
    });
    
    app.controller("pagetwoctrl",funtion($scope,Page){
    
    Page.setTitle("pagetwo");
    
    });
    

    PS:-第二个更实用:)

    信用:- https://stackoverflow.com/a/12506795/1632286

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2014-04-29
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多