如何在AngularJs中使用ng-repeat进行词典?

本文翻译自:How to use ng-repeat for dictionaries in AngularJs?

I know that we can easily use ng-repeat for json objects or arrays like: 我知道我们可以轻松地对json对象或数组使用ng-repeat ,如:

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

but how can we use the ng-repeat for dictionaries, for example: 但是我们如何才能将ng-repeat用于词典,例如:

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

I want to use that with users dictionary: 我想用用户词典:

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

Is it possible?. 可能吗?。 If yes, how can I do it in AngularJs? 如果是,我怎么能在AngularJs中做到这一点?

Example for my question: In C# we define dictionaries like: 我的问题示例:在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)
{
}

Is there a build-in function that returns the values from a dictionary like in c#? 是否有内置函数从c#中返回字典中的值?


#1楼

参考:https://stackoom.com/question/Oi4n/如何在AngularJs中使用ng-repeat进行词典


#2楼

You can use 您可以使用

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

See ngRepeat documentation . 请参阅ngRepeat文档 Example: http://jsfiddle.net/WRtqV/1/ 示例: http//jsfiddle.net/WRtqV/1/


#3楼

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary. JavaScript开发人员倾向于将上述数据结构称为对象或哈希而不是字典。

Your syntax above is wrong as you are initializing the users object as null. 当您将users对象初始化为null时,上面的语法是错误的。 I presume this is a typo, as the code should read: 我认为这是一个拼写错误,因为代码应该是:

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

To retrieve all the values from a hash, you need to iterate over it using a for loop: 要从哈希中检索所有值,您需要使用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;
};

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. 如果您计划在JavaScript中使用数据结构进行大量工作,那么下划线.js库绝对值得一看。 Underscore comes with a values method which will perform the above task for you: Underscore附带一个values方法 ,可以为您执行上述任务:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :)) 我自己不使用Angular,但我很确定会有一个方便的方法来迭代哈希的值(啊,我们去,Artem Andreev提供上面的答案:))


#4楼

I would also like to mention a new functionality of AngularJS ng-repeat , namely, special repeat start and end points . 我还想提一下AngularJS ng-repeat的新功能,即特殊的重复起点终点 That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element. 添加了该功能是为了重复一系列 HTML元素,而不是仅重复单个父HTML元素。

In order to use repeater start and end points you have to define them by using ng-repeat-start and ng-repeat-end directives respectively. 要使用转发器起点和终点,必须分别使用ng-repeat-startng-repeat-end指令定义它们。

The ng-repeat-start directive works very similar to ng-repeat directive. ng-repeat-start指令与ng-repeat指令非常相似。 The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-end is placed (including the tag with ng-repeat-end ). 区别在于将重复所有 HTML元素(包括它定义的标记),直到放置ng-repeat-end的结束HTML标记(包括带有ng-repeat-end的标记)。

Sample code (from a controller): 示例代码(来自控制器):

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

Sample HTML template: 示例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>

Output would look similar to the following (depending on HTML styling): 输出看起来类似于以下内容(取决于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]
======================

As you can see, ng-repeat-start repeats all HTML elements (including the element with ng-repeat-start ). 如您所见, ng-repeat-start重复所有HTML元素(包括带有ng-repeat-start的元素)。 All ng-repeat special properties (in this case $first and $index ) also work as expected. 所有ng-repeat特殊属性(在本例中$first$index )也按预期工作。


#5楼

In Angular 7, the following simple example would work (assuming dictionary is in a variable called d ): 在Angular 7中,以下简单示例将起作用(假设字典位于名为d的变量中):

my.component.ts: my.component.ts:

keys: string[] = [];  // declaration of class member 'keys'
// component code ...

this.keys = Object.keys(d);

my.component.html: (will display list of key:value pairs) my.component.html :(将显示键:值对的列表)

<ul *ngFor="let key of keys">
    {{key}}: {{d[key]}}
</ul>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值