【问题标题】:How to change the page title using a variable in Angular Js? [duplicate]如何使用 Angular Js 中的变量更改页面标题? [复制]
【发布时间】:2017-10-28 07:01:16
【问题描述】:

我正在使用以下代码在 AngularJs 中动态更改我的标题:

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

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            title: 'My Tagline',
            controller : 'IndexController',
            templateUrl : 'static/app_partials/index.html'
        })
        .when('/categories/:categoryPk/', {
            title: $scope.category.name,
            controller : 'CategoryController',
            templateUrl : 'static/app_partials/category.html'
        })
        .otherwise({ redirectTo : '/' });
}]);

HTML

<title ng-bind="'My Brand - ' + title">My Brand</title>

所以,对于IndexController,标题只是一个简单的字符串,所以这种方法效果很好。但是,对于我的CategoryController,我希望从变量生成标题,特别是$scope.category.name,我在控制器代码中对其进行了初始化。我怎样才能做到这一点?有什么帮助吗?

【问题讨论】:

标签: javascript angularjs angular-routing


【解决方案1】:

如下使用ng-bind-template

<title ng-bind-template="My Brand - {{$root.title}}">My Brand</title>

【讨论】:

  • 还必须从路由配置中删除title: $scope.category.name,...那里没有$scope
  • 那么如何将我的变量作为控制器的标题?
  • @TahmidKhanNafee 你可以在routeChangeSuccess even 处理程序中做到这一点
【解决方案2】:

查看ng-meta 在您的AngularJS 单页应用程序中设置动态元标记

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2017-01-23
    • 2017-10-19
    • 1970-01-01
    相关资源
    最近更新 更多