无法使用角度局部存储

时间:2014-08-25 14:20:08

标签: javascript angularjs module controller local-storage

这是我的代码:

   angular.module('MyModule').controller('MyController', ['$scope', '$stateParams','$location', '$http','LocalStorageModule',
function($scope, $stateParams, $location, $http, localStorageService) {

        localStorageService.add('test', 'val');
]);

任何想法都错了吗?

我在FF浏览器中获得异常 - 未知提供者localstorageservice

Firebug错误

Error: [$injector:unpr] Unknown provider: LocalStorageModuleProvider <-   LocalStorageModule
http://errors.angularjs.org/1.2.20/$injector/unpr?p0=LocalStorageModuleProvider%20%3C-     %20LocalStorageModule
    at http://127.1.0.0/lib/angular/angular.js:78:12

1 个答案:

答案 0 :(得分:18)

我们应该向inejctor询问 'localStorageService' 而不是 'LocalStorageModule'

所以代码应如下所示:

angular
    .module('MyModule')
    .controller('MyController', ['$scope', '$stateParams','$location'
                                , '$http'
                                // instead of this
                                // ,'LocalStorageModule',
                                // use this
                                ,'localStorageService',
               function($scope, $stateParams, $location, $http, localStorageService) 
    {
        //localStorageService.add('test', 'val');
        localStorageService.set('test', 'val');
    }]);

当我们初始化模块时,我们必须包含本地存储模块

angular
    .module('MyModule', [
       'LocalStorageModule', 
        ...
    ])

并且如此处所述:

我们应该使用 .set()

// To add to local storage
localStorageService.set('localStorageKey','Add this!');