将控制器变量设置为角度状态的页面标题

时间:2018-04-27 06:34:56

标签: javascript html angularjs angular-ui-router

.state('access.surveys', {
                url: '/surveys',
                templateUrl: 'app/tpl/feedback/index.html',
                data: {
                    pageTitle: 'XYZ Client Survey'
                },
                controller: 'surveysCtrl',
                resolve: {
                    deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load([], {
                            insertBefore: '#lazyload_placeholder'
                        })
                            .then(function () {
                                return $ocLazyLoad.load([
                                    'app/controllers/surveysCtrl.js',
                                ]);
                            });
                    }]
                }
            })

我在“surveysCtrl”中有一个变量$ scope.companyname。如何将我的页面标题设置为:

pageTitle: '{{companyname}} Client survey'

1 个答案:

答案 0 :(得分:0)

你可以创建一个从ui-router

监听转换挂钩的指令
app.directive('pageTitle', function () {

    var controller = ['$scope', '$transitions', function ($scope, $transitions) {

          $scope.title = '';
          $transitions.onSuccess({}, function(transition) {
              $scope.title = transition.to().data.pageTitle;
            });

      }],
      template = '<h1>{{title}}</h1><ul>';

      return {
          restrict: 'EA',
          controller: controller,
          template: template
      };
});

然后在html中添加title指令

<page-title />

注意:$ transition用于ui.router&gt; = 1.0。

对于以前的版本,请注入$ rootScope并侦听$ stateChangeSuccess事件

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ 
            $scope.title =toParams.pageTitle;
 })