Angular rootScope在模板中不可见

时间:2016-04-27 10:48:37

标签: angularjs angular-ui-router

我更改了$state元素上的课程,具体取决于我的网站当前显示的<body class="{{specialClass}}">

我说specialClass,其中$rootScoperun的变量。此变量在我的主应用程序模块的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"变量,因此class属性为空。与此同时,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> 模板:

Config::inst()->update('MyDataObject', 'translate',<SET ME HERE>);

更令人抓狂的是,当我使用Webpack dev服务器在开发中提供前端时,它可以正常运行,该类已切换。但是,当我在Django的生产中使用它时,事实并非如此。两种情况都存在控制台输出。

1 个答案:

答案 0 :(得分:1)

根据ngClass关于数组语法,我在我自己的应用程序中尝试这个:

(() =>
{
    '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>