Search code examples
javascriptember.jsember-cli

Emberjs toggle effect of dynamic data


I have a table loaded with dynamic data from an api. The <td></td> displays a company name and when clicked I want a div that has the companies information to be displayed. I saw a few examples and this is what I did:

Here is my handlebars:

{{#each m in model}}
    <tr>
        <td >
            <p {{ action 'displayDetails' }}>{{m.name}}</p>
            {{#if showDetails}}
                <div class="company_details">
                    <p><strong>Wesbite URL: </strong><a href="{{m.website}}">{{m.website}}</a></p>
                    <p><strong>Development Wesbite URL: </strong><a href="{{m.dev_website}}">{{m.dev_website}}</a></p>
                </div>
            {{/if}} 
        </td>
    </tr>
{{/each}}

as you can see when you click on the name of the company the displayDetails action is called

here is my controller:

export default Ember.ArrayController.extend({
    showDetails: false,

    actions: {
        displayDetails: function(){
            this.toggleProperty('showDetails');
        }
    }
});

This works great; however if I click the company name all of the company details are displayed not just the company I clicked on. I obviously just want to display the specific detail of the company I clicked on how can I go about this?


Solution

  • Add a property to each item in the model named something like isDetailsShown.

    You can modify you action by passing the item into the method.

    <p {{ action 'displayDetails' item}}>{{m.name}}</p>
    

    In the action, just toggle the property of the passed in item.

    displayDetails: function(item){
      item.toggleProperty('isDetailsShown');
    }
    

    Finally modify the if condition in the template to look like

    {{#if item.isDetailsShown}}