【问题标题】:Angularjs rootscope not updating ngClassAngularjs rootscope不更新ngClass
【发布时间】:2013-06-20 07:42:56
【问题描述】:

我很确定这又是一件愚蠢的事情。我正在学习 angularjs,所以我还没有得到完整的范围,但我已经到了。我尝试了所有方法并真正搜索了我能找到的任何东西,但似乎没有任何效果。

我正在尝试在我的布局文件中执行 ng-class="..." 但表达式已在我的控制器中设置但不知何故它没有呈现。当我把它放在我的 ng-view 文件中时,它会被渲染。我知道他只渲染文件的一部分,但我希望他也能在 ng-view 上渲染 ng-class。这是可能的还是在部分html文件中放入一个div更容易。

简单的html文件

<body>
<ng-view ng-class="{ 'splash': splash=='splash' }"></ng-view>
</body>

我的控制器

angular.module('xxx.splash')
    .controller('IndexCtrl', function($scope, $rootScope, config) {
        $rootScope.splash = 'splash';

        $scope.login = function(e) {
            alert('Soon. How soon? Very soon.');
        }
    });

【问题讨论】:

    标签: angularjs angularjs-scope


    【解决方案1】:

    当您在根范围内定义变量时,您无法像在本地范围内定义它一样访问它。 $rootScope 变量可以在 AngularJS 模板中使用 $root.&lt;variableName&gt; 访问,因此您的 HTML 文件应更改为:

    <body>
    <ng-view ng-class="{ 'splash': $root.splash=='splash' }"></ng-view>
    </body>
    

    你可以在这个demo中看到$scope$rootScope的区别

    【讨论】:

    • 为什么在html端不叫“$rootScope”?
    • @DavidKarlsson 因为它已经是一个范围。每个作用域都有一个属性$root 指向模板上的$rootScope,你会得到一些也有这个指针的作用域,因此得名。尽管将其重命名可能不会那么令人困惑...
    猜你喜欢
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2023-03-14
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多