Steve Steve - 6 months ago 16
JSON Question

Angular JS set value of clicked object in ng-repeat

I have an ng-repeat which iterates object like:

{
"id": 1,
"title": "Lorem Ipsum",
"base_text": "Lorem ispum",
"read_more_text": "lorem ipsum",
"show_details": false,
"button_label": "Read More",
"button_link": "",
"image": ""
},


Inside the ng-repeat in the html, there is a button which I want to toggle the value of that
show_details
property.

So, I have an
ng-click
handler:

<div class="hero-item" ng-repeat="h in dash.heroItems">
<div>
<h3>{{h.title}}</h3>
<p>{{h.base_text}}</p>
<p ng-if="h.show_details">{{h.read_more_text}}</p>
</div>
<div>
<button ng-click="dash.showHeroDetails(h.id)">{{h.button_label}}</button>
</div>
</div>


So I am passing the repeat instance's
ID
property. But here I am stuck, I can't get the correct syntax for toggling that boolean property.

I have this so far:

_this.showHeroDetails = function (item) {
_this.show_details = item;
};


which is clearly wrong...

Answer

From template, pass the object.

<div>
    <button ng-click="dash.showHeroDetails(h)">{{h.button_label}}</button>
</div>

In script, just toggle the value.

_this.showHeroDetails = function (item) {
    item.show_details = !item.show_details;
 };