ChatGPT解决这个技术问题 Extra ChatGPT

How to use ng-repeat for dictionaries in AngularJs?

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#?

What is the difference between a dictionary and a JSON object? I believe there is none in javascript!
@markmarijnissen: A JSON object has more stringent syntax rules than a JavaScript object. And, as we’re already in Pedant’s Corner, there’s no such thing as a “Dictionary” in JavaScript. We just call them objects.

D
DLeh

You can use

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

See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/


This is not what I asked but exacly what I wanted. Thank you Artem Andreev
How can we use filter in this ng-repeat. Its not working in my case when i am using a search filter. Say
  • {{name}}: {{age}}
  • ...
    @Shekhar Filter "filter" works only with arrays. You can try to create feature request.
    Good to see some commonality with python :)
    You can get filter feature even on dictionaries(objects) by using the ng-if statement.. like for example:
  • {{obj.name}} {{obj.surname}}
  • ... where items is a set of persons indexed by some key.
    T
    Tom

    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 and ng-repeat-end directives respectively.

    The ng-repeat-start directive works very similar to ng-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 where ng-repeat-end is placed (including the tag with 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:

    <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):

    ==== 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). All ng-repeat special properties (in this case $first and $index) also work as expected.


    Error: [$compile:uterdir] Unterminated attribute, found 'ng-repeat-start' but no matching 'ng-repeat-end' found.
    @zloctb you must have skipped <div ng-repeat-end>..</div> in your markup
    J
    JonnyReeves

    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:

    // 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:

    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. Underscore comes with a values method which will perform the above task for you:

    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 :))


    +1 for underscore.js and these useful informations. Thank You Johnny!
    R
    Ron Kalian

    In Angular 7, the following simple example would work (assuming dictionary is in a variable called d):

    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)

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