2

I have a JSON object that contains a map of values. The keys of these map item are predefined. I use ng-repeat to create a button for each map item and I pass the item to the method via ng-click.

To execute a certain call, I now need the key of the item. How can I get the key of the given item?

The JSON looks like

"map": {
    "0": {
      "id": 1,
      "value": "123",
    },
    "1": {
      "id": 5,
      "value": "567",
    }
}

.html

<div ng-repeat="item in object.map">
    <button ng-click="load(item)" type="button">A</button>
</div>

app.js

$scope.load= function(item) {
    // HOW TO GET THE KEY OF THE GIVEN MAP ITEM
};

3 Answers 3

2

You can iterate over the properties of this object, getting the pair (key, item), using the following syntax:

<div ng-repeat="(key, item) in object.map">
    <button ng-click="load(key, item)" type="button">A</button>
</div>

In this way, you pass the key of the item to the load function. In this link, you can find more details about this syntax for ng-repeat.

Sign up to request clarification or add additional context in comments.

Comments

1

This may help you.

<div ng-repeat="(key, value) in object.map">
    <button ng-click="load(key,value)" type="button">A</button>
</div>

Comments

0

Another approach you can use is getting object into your controller and acess keys there using Object.keys(objname).

app.js will look sommething like this:

$scope.load= function(item) {
  let key = Object.keys(item);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.