Yasin Yildiz Yasin Yildiz - 2 months ago 10
AngularJS Question

ng-if should show only one object

Hi dear Stackoverflow Community i have a problem. First here is my Code:

html:

<md-card md-theme-watch flex="100" ng-repeat="offer in company.offers">

<md-button class="md-fab md-mini md-primary md-fab-oi" aria-label="copy" ng-click="company.setEditVisibility()">

<oi-offer-edit offer="offer" is-change="true" ng-if="company.isEditVisible">
</oi-offer-edit>
</md-card>


My controller:

function setEditVisibility(){
vm.isEditVisible = !vm.isEditVisible;
}


it work just fine the problem is that it shows oi-offer-edit directive for every repeated Object.
If you need more info pls dont hesitate to ask!

Answer

If you don't want to touch your markup and want the oi-offer-edit element to be repeated, you have to use a boolean property on the offer object itself:

<md-card md-theme-watch flex="100" ng-repeat="offer in company.offers">
    <md-button class="..." ng-click="offer.formVisible = !offer.formVisible">

    <oi-offer-edit offer="offer" is-change="true" ng-if="offer.formVisible">             
    </oi-offer-edit>
</md-card>

Solution before i realized, that you want to have that directive in every md-card:

You might want to place your oi-offer-edit element outside your ng-repeat container, because as far as i see it in your snippet, you only need one with the offer-data of the selected company.offers.

So you could just cache the offer on the click handler and make your oi-offer-edit visible. Something like this:

<md-card md-theme-watch flex="100" ng-repeat="offer in company.offers">
    <md-button class="..." ng-click="company.setEditVisibility(offer)">
</md-card>

<oi-offer-edit offer="currentSelectedOffer" is-change="true" ng-if="company.isEditVisible">             
</oi-offer-edit>

function setEditVisibility(selectedOffer){
     vm.currentSelectedOffer = selectedOffer;
     vm.isEditVisible = !vm.isEditVisible;
}