简体   繁体   English

将对象键作为参数进行参数检索

[英]Passing object key as an argument for parameter retrieval

I've built an AngularJS factory: 我建立了一个AngularJS工厂:

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. 我将在localStorage中存储多个对象,并且我希望可以灵活地通过工厂检索它们,而不是将$ localStorage依赖项与工厂一起注入。

I strongly believe the issue is lying in the factory's parameter passing. 我坚信问题出在工厂的参数传递中。 Some JavaScript hack that my brain is not processing. 我的大脑没有处理的一些JavaScript hack。 LOL. 大声笑。 Any ideas? 有任何想法吗? ^_^ ^ _ ^

UPDATE: Sorry guys, I totally forgot the error~ Basically, when this code is executed, I get "ReferenceError: objA is not defined" 更新:对不起,我完全忘记了这个错误〜基本上,当执行此代码时,我得到“ ReferenceError:objA未定义”

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. 在您的.get()方法内部,您尝试根据传入的值来检索属性,但实际上是在寻找不存在的属性storageItem If you want to use the value of storageItem , you need to use the bracket syntax. 如果要使用storageItem的值, storageItem需要使用方括号语法。

return $localStorage[storageItem];

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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