我正在尝试在我的 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/