javascript - ng-cookie 和主题切换器

标签 javascript angularjs cookies

我正在尝试在我的 Controller 中添加 cookie 来切换它们。
这是我的代码:

Common.css is my default css for every user

HeaderCtrl.js

myApp.controller('headerCtrl', function ($scope, $cookieStore) {
    var currentTheme = $cookieStore.get("App/Common/Style/Common/common.css");

    $scope.changeTheme = function (theme) {
        if (!currentTheme) {
            $scope.currentTheme = "App/Common/Style/Common/common.css";
        }
        else if(theme === 'red'){
            $scope.currentTheme = "App/Common/Style/Switcher/styleRed.css";
        } else if (theme === 'common') {

            $scope.currentTheme = "App/Common/Style/Switcher/common.css";

        } 
        $cookieStore.put("App/Common/Style/Common/common.css", $scope.currentTheme);
    };


});  

HTML

<link ng-href="{{currentTheme}}" rel="stylesheet" />    

更新
那是 fiddle我从 .

它改变了我的主题,但 cookie 不工作。
我错过了什么吗?

最佳答案

我认为问题是您在 Controller 加载时第一次访问 cookie 但您没有将其分配给范围。

myApp.controller('headerCtrl', function ($scope, $cookieStore) {

    //assign to scope
    $scope.currentTheme = $cookieStore.get("App/Common/Style/Common/common.css");

    $scope.changeTheme = function (theme) {

        if(theme === 'red'){
            $scope.currentTheme = "App/Common/Style/Switcher/styleRed.css";
        } else if (theme === 'common') {

            $scope.currentTheme = "App/Common/Style/Switcher/common.css";

        } 
        $cookieStore.put("App/Common/Style/Common/common.css", $scope.currentTheme);
    };

});  

这就是页面加载时它无法绑定(bind) {{currentTheme }} 但当您调用 changeTheme() 时它开始工作的原因。

关于javascript - ng-cookie 和主题切换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27701974/

相关文章:

javascript - 模块解析失败 : The keyword 'interface' is reserved using turbo repo Next. js 13

如果在网页中找到特定文本,javascript将显示警报消息

angularjs - Angular.js 与 React.js 与 php mvc (Laravel)

javascript - 从客户端删除任何 session

javascript - 大写破折号后的字母并删除破折号

javascript - 使用 JavaScript 重定向

javascript - 在设置 cookie 后运行脚本而不重新加载页面

cookies - Asp.net Core 2.0 Identity.TwoFactorRememberMe 过期

javascript - 控制台日志为 $index 返回 'undefined'。 Angular

mysql - 带有 Angular JS 和 MySql 的表在转发器中显示重复的键