我试图在我的控制器中添加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无效。
我错过了什么吗?
答案 0 :(得分:1)
我认为问题是您在控制器加载时第一次访问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);
};
});
这是页面加载它不能用于绑定{{currentTheme }}
但是当你调用changeTheme()
时它开始工作的原因。