如何将带有AngularJS ngStorage的JSON变量存储到$ sessionStorage

时间:2016-09-14 13:32:32

标签: angularjs sessionstorage ng-storage

我有以下变量,可以很容易地转换为JSON-String:

ul:last-child:nth-child(2) { ... }

在我的Controller中,我希望将此变量添加到范围内,如:

string s = "AA";
byte byteValue = 0; 
try
{
    byteValue = byte.Parse(s, NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier);
}
catch (Exception e)
{
     Console.WriteLine(e);
}

Console.WriteLine("String value: 0x{0}, byte value: {1}", s, byteValue);

然后我希望它存储在$ sessionStorage上,如:

var data = {
    ball: {
        colour: "",
        size: "",
        price: ""
    },
    toys: []
}

页面刷新后,$scope.data = angular.copy(data) 再次为空。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这是我的代码的工作方式:

    $scope.$storage = $sessionStorage;

    if (typeof $scope.$storage.data !== 'undefined') {
        $scope.data = $scope.$storage.data;
    } else {
        $scope.data = angular.copy(data);
        $scope.$storage.data = $scope.data;
    }

更短的解决方案是:

    $scope.cv = $scope.$storage.cv || angular.copy(cv);
    $scope.$storage.cv = $scope.cv;