json 如何在 AngularJs 中为字典使用 ng-repeat?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11985863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use ng-repeat for dictionaries in AngularJs?
提问by Vural
I know that we can easily use ng-repeatfor json objects or arrays like:
我知道我们可以轻松地将ng-repeat用于 json 对象或数组,例如:
<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# 一样从字典中返回值?
回答by Artem Andreev
You can use
您可以使用
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
回答by Tom
I would also like to mention a new functionality of AngularJS ng-repeat, namely, special repeat startand end points. That functionality was added in order to repeat a seriesof HTML elements instead of just a singleparent HTML element.
我还想提一下AngularJS 的ng-repeat一个新功能,即特殊的重复起点和终点。添加该功能是为了重复一系列HTML 元素,而不仅仅是单个父 HTML 元素。
In order to use repeater start and end points you have to define them by using ng-repeat-startand ng-repeat-enddirectives respectively.
为了使用中继器的起点和终点,您必须分别使用ng-repeat-start和ng-repeat-end指令来定义它们。
The ng-repeat-startdirective works very similar to ng-repeatdirective. The difference is that is will repeat allthe HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-endis placed (including the tag with ng-repeat-end).
该ng-repeat-start指令的工作方式与ng-repeat指令非常相似。不同之处在于它会重复所有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-startrepeats all HTML elements (including the element with ng-repeat-start). All ng-repeatspecial properties (in this case $firstand $index) also work as expected.
如您所见,ng-repeat-start重复所有 HTML 元素(包括带有 的元素ng-repeat-start)。所有ng-repeat特殊属性(在本例中$first和$index)也按预期工作。
回答by JonnyReeves
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 usersobject as null. I presume this is a typo, as the code should read:
当您将users对象初始化为 null 时,您上面的语法是错误的。我认为这是一个错字,因为代码应该是:
// 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.jslibrary is definitely worth a look. Underscore comes with a valuesmethodwhich will perform the above task for you:
如果您计划在 JavaScript 中使用数据结构进行大量工作,那么underscore.js库绝对值得一看。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 提供了上面的答案:))
回答by Ron Kalian
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>

