I know that we can easily use ng-repeat for json objects or arrays like:
<div ng-repeat="user in users"></div>
but how can we use the ng-repeat for dictionaries, for example:
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?
Example for my question: In C# we define dictionaries like:
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#?
JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.
Your syntax above is wrong as you are initializing the
users
object as null. I presume this is a typo, as the code should read:To retrieve all the values from a hash, you need to iterate over it using a for loop:
If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a
values
method which will perform the above task for you: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 :))
I would also like to mention a new functionality of AngularJS
ng-repeat
, namely, special repeat start and end points. That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element.In order to use repeater start and end points you have to define them by using
ng-repeat-start
andng-repeat-end
directives respectively.The
ng-repeat-start
directive works very similar tong-repeat
directive. The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag whereng-repeat-end
is placed (including the tag withng-repeat-end
).Sample code (from a controller):
Sample HTML template:
Output would look similar to the following (depending on HTML styling):
As you can see,
ng-repeat-start
repeats all HTML elements (including the element withng-repeat-start
). Allng-repeat
special properties (in this case$first
and$index
) also work as expected.You can use
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/