简体   繁体   中英

Passing object key as an argument for parameter retrieval

I've built an AngularJS factory:

angular.module('app.services', [])

.factory('StorageService', function($localStorage) {
    $localStorage.$default({
        objA : ['foo','bar'],
        objB : []
    });
    var _getByKey = function(storageItem){
        return $localStorage.storageItem;
    }

    return {
        get : _getByKey
    };

});

In my controller, I'm trying to retrieve it as such:

angular.module('app.controllers', [])
.controller('testCtrl', function($scope, StorageService) {
    console.log(StorageService.get(objA));
}

I will be having several objects stored in the localStorage and I want a flexibility to retrieve them via the factory rather than injecting the $localStorage dependency together with the factory.

I strongly believe the issue is lying in the factory's parameter passing. Some JavaScript hack that my brain is not processing. LOL. Any ideas? ^_^

UPDATE: Sorry guys, I totally forgot the error~ Basically, when this code is executed, I get "ReferenceError: objA is not defined"

Your syntax here is not quite right. What you are trying to do is pass the property name you want to retrieve; What you are actually doing is passing a variable, which hasn't been declared yet.

So the first part you need to change is:

console.log(StorageService.get('objA'));

Pass a string value, rather than a variable.

Inside your .get() method, you are attempting to retrieve the property based on the value that was passed in, but what you are actually doing is looking for the property storageItem , which won't exist. If you want to use the value of storageItem , you need to use the bracket syntax.

return $localStorage[storageItem];

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM