【问题标题】:How to use ng-repeat for dictionaries in AngularJs?如何在 AngularJs 中对字典使用 ng-repeat?
【发布时间】:2012-08-12 17:25:09
【问题描述】:

我知道我们可以轻松地将 ng-repeat 用于 json 对象或数组,例如:

<div ng-repeat="user in users"></div>

但是我们如何将 ng-repeat 用于字典,例如:

var users = null;
users["182982"] = "{...json-object...}";
users["198784"] = "{...json-object...}";
users["119827"] = "{...json-object...}";

我想将它与用户字典一起使用:

<div ng-repeat="user in users"></div>

有可能吗?如果是,我该如何在 AngularJs 中做到这一点?

我的问题示例: 在 C# 中,我们定义如下字典:

Dictionary<key,value> dict = new Dictionary<key,value>();

//and then we can search for values, without knowing the keys
foreach(var val in dict.Values)
{
}

是否有像 c# 一样从字典中返回值的内置函数?

【问题讨论】:

标签: angularjs json dictionary angularjs-ng-repeat


【解决方案1】:

你可以使用

<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>

ngRepeat documentation。示例:http://jsfiddle.net/WRtqV/1/

【讨论】:

  • 这不是我问的,而是我想要的。谢谢阿特姆·安德烈耶夫
  • 我们如何在这个 ng-repeat 中使用过滤器。当我使用搜索过滤器时,它在我的情况下不起作用。说
  • {{name}}: {{age}}李>...
  • @Shekhar Filter "filter" 仅适用于数组。您可以尝试创建功能请求。
  • 很高兴看到与 python 的一些共性:)
  • 您甚至可以通过使用 ng-if 语句在字典(对象)上获得过滤功能。例如:
  • {{obj.name}} {{obj.surname}}
  • ... 其中 items 是由某个键索引的一组人员。
    【解决方案2】:

    JavaScript 开发人员倾向于将上述数据结构称为对象或哈希,而不是字典。

    您将users 对象初始化为空时,上面的语法是错误的。我认为这是一个错字,因为代码应该是:

    // Initialize users as a new hash.
    var users = {};
    users["182982"] = "...";
    

    要从哈希中检索所有值,您需要使用 for 循环对其进行迭代:

    function getValues (hash) {
        var values = [];
        for (var key in hash) {
    
            // Ensure that the `key` is actually a member of the hash and not
            // a member of the `prototype`.
            // see: http://javascript.crockford.com/code.html#for%20statement
            if (hash.hasOwnProperty(key)) {
                values.push(key);
            }
        }
        return values;
    };
    

    如果您打算在 JavaScript 中使用数据结构做大量工作,那么 underscore.js 库绝对值得一看。下划线带有一个values method,它将为您执行上述任务:

    var values = _.values(users);
    

    我自己不使用 Angular,但我很确定会内置一种方便的方法来迭代哈希值(啊,好了,Artem Andreev 提供了上面的答案 :))

    【讨论】:

    • +1 表示 underscore.js 和这些有用的信息。谢谢你,约翰尼!
    【解决方案3】:

    我还要提一下AngularJS ng-repeat的一个新功能,即特殊重复startendpoints。添加该功能是为了重复 series 的 HTML 元素,而不仅仅是 单个 父 HTML 元素。

    为了使用中继器起点和终点,您必须分别使用ng-repeat-startng-repeat-end 指令来定义它们。

    ng-repeat-start 指令的工作方式与ng-repeat 指令非常相似。不同之处在于它将重复 所有 HTML 元素(包括定义它的标记)直到放置 ng-repeat-end 的结束 HTML 标记(包括带有 ng-repeat-end 的标记)。

    示例代码(来自控制器):

    // ...
    $scope.users = {};
    $scope.users["182982"] = {name:"John", age: 30};
    $scope.users["198784"] = {name:"Antonio", age: 32};
    $scope.users["119827"] = {name:"Stephan", age: 18};
    // ...
    

    示例 HTML 模板:

    <div ng-repeat-start="(id, user) in users">
        ==== User details ====
    </div>
    <div>
        <span>{{$index+1}}. </span>
        <strong>{{id}} </strong>
        <span class="name">{{user.name}} </span>
        <span class="age">({{user.age}})</span>
    </div>
    
    <div ng-if="!$first">
       <img src="/some_image.jpg" alt="some img" title="some img" />
    </div>
    <div ng-repeat-end>
        ======================
    </div>
    

    输出类似于以下内容(取决于 HTML 样式):

    ==== User details ====
    1.  119827 Stephan (18)
    ======================
    ==== User details ====
    2.  182982 John (30)
    [sample image goes here]
    ======================
    ==== User details ====
    3.  198784 Antonio (32)
    [sample image goes here]
    ======================
    

    如您所见,ng-repeat-start 重复所有 HTML 元素(包括带有ng-repeat-start 的元素)。所有ng-repeat 特殊属性(在本例中为$first$index)也可以按预期工作。

    【讨论】:

    • 错误:[$compile:uterdir] 未终止的属性,找到 'ng-repeat-start' 但没有找到匹配的 'ng-repeat-end'。
    • @zloctb 你必须在标记中跳过&lt;div ng-repeat-end&gt;..&lt;/div&gt;
    【解决方案4】:

    在 Angular 7 中,以下简单示例可以工作(假设字典位于名为 d 的变量中):

    my.component.ts:

    keys: string[] = [];  // declaration of class member 'keys'
    // component code ...
    
    this.keys = Object.keys(d);
    

    my.component.html:(将显示键:值对列表)

    <ul *ngFor="let key of keys">
        {{key}}: {{d[key]}}
    </ul>
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签