2016-04-27 21 views
0

我更改了<body>元素上的类,具体取决于我的网站当前显示哪个$state模板中不可见的角rootScope

我说<body class="{{specialClass}}">,其中specialClass是一个变量$rootScope。这个变量被设置在我的主要应用模块的run块:

angular.module("main", [dependencies]) 
    .run(function($rootScope) { 
    $rootScope.$on('$stateChangeSuccess', function(event, currentState){ 
     switch (currentState.name) { 
      case "about": 
       console.log("I'm on landing page, set specialClass in $rootScope"); 
       $rootScope.specialClass = 'landing-page'; 
       break; 
      default: 
       $rootScope.specialClass = ''; 
       break; 
     } 
    }) 
}); 

出于某种原因,我的模板不看specialClass变量,因此该类属性为空。与此同时,出现"I'm on landing page, set specialClass in $rootScope"

怎么了?

我的全index.html模板:

<html> 
    <head> 
     <base href="/"> 
     <meta charset="UTF-8"> 
     <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
     <title>My project</title> 
    </head> 
    <body ng-app="main" class="{{specialClass}}"> 
     <ui-view> 
      This is my application. 
     </ui-view> 
    </body> 
</html> 

什么是更疯狂,当我与的WebPack开发服务器开发服务前端,它工作正常,类切换。但是当我用Django在生产中使用它时,事实并非如此。控制台输出在两种情况下都存在。根据ngClass有关数组语法

+2

尝试使用纳克级的指令 – Revive

+0

中标记您的引导你的应用程序? ? 'ngApp'指令必须包含body标签。 – Hitmands

+0

该模板在哪里? –

回答

1

,我尝试这在我自己的应用程序:

(() => 
{ 
    'use strict'; 
    angular.module('app', [/**'ng-routing'**/]) 
    .run(['$rootScope', function($rootScope) 
    { 
     // $rootScope.specialClass = ''; // no need, since an empty string is falsy as well as undefined OR null 
     $rootScope.$on('$stateChangeSuccess', function(event, currentState) 
     { 
      switch (currentState.name) 
      { 
       case "about": 
        $rootScope.specialClass = 'landing-page'; 
        break; 
      } 
     }); 
    }]); 
})(); 

...

<!DOCTYPE html> 
<html xmlns:ng="http://angularjs.org" ng-app="app" ng-cloak ng-strict-di> 
    <head> 
     <meta charset="utf-8"> 
     <title>{{app.title}}</title> 
     <script src="web/libs/jquery/dist/jquery.js"></script> 
     <script src="web/libs/angular/angular.js"></script> 
     <script src="web/js/javascript.js"></script> 
    </head> 
    <body ng-class="[specialClass]"> 
    </body> 
</html>