当我使用广播更改范围变量时,为什么ng-class不能处理我的指令?

时间:2014-07-28 18:07:35

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个指令,它是一个切换按钮,用于更改页面的主题。

该指令的代码是......

app.directive('twoOptionThemeSwitch', function () {
    return {
        scope: {},
        restrict: 'A',
        replace: 'true',
        templateUrl: 'app/themes/partials/twoOptionThemeSwitch.html',
        controller: 'twoOptionThemeSwitch',
        link: function (scope, elem, attrs) {
            elem.bind('click', scope.switchTheme);
        }
    };
});

此控制器是......

app.controller('twoOptionThemeSwitch', function ($scope, $rootScope) {

    $rootScope.$on('switchTheme', function (event, theme) {
        $scope.selectedTheme = theme;
        $scope.inverseButton = theme == 'theme-dark';
    });

    $scope.switchTheme = function () {
        if ($scope.selectedTheme == 'theme-bright') {
            $rootScope.$broadcast('switchTheme', 'theme-dark');
        } else {
            $rootScope.$broadcast('switchTheme', 'theme-bright');
        }
    }

    $rootScope.$broadcast('switchTheme', 'theme-bright');
});

这是标记...

<div class="btn-group" data-toggle="buttons" id="theme-switcher">
    <label class="btn" ng-class="{'btn-inverse' : inverseButton, 'active' : !inverseButton}">
        <input type="radio" name="theme-switcher"><i class="icon-sun"></i> Bright
    </label>
    <label class="btn" ng-class="{'btn-inverse' : inverseButton, 'active' : inverseButton}">
        <input type="radio" name="theme-switcher"><i class="icon-moon"></i> Dark
    </label>
</div>

当我在初始化期间从控制器调用$ broadcast时,它正确地设置了类。但是,当我单击按钮时,类不会改变,但是在调试时我注意到$ on被正确触发,所以我知道范围变量正在设置。

0 个答案:

没有答案