Skip to content Skip to sidebar Skip to footer

Ng-if Should Show Only One Object

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

Solution 1:

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;
}

Solution 2:

it will because you have bounded to each ng-repeat object .


Solution 3:

If you want to toggle the visibility of oi-offer-edit independently of each offer object then you should move the boolean flag you're checking in the ng-if directive into the offers array.

Check the below example it will help you accomplish what you want to do.

angular
   .module('demo', [])
   .controller('DefaultController', DefaultController);
   
   function DefaultController() {
    var vm = this;
    vm.company = {
      offers: [
        { id: 1, name: 'Offer 1' },
        { id: 2, name: 'Offer 2' },
        { id: 3, name: 'Offer 3' }
      ]
    };
    
    vm.setEditVisibility = setEditVisibility;
    
    function setEditVisibility(id) {
      for (var i = 0; i < vm.company.offers.length; i++) {
        if (vm.company.offers[i].id === id) {
          vm.company.offers[i].isEditVisible = !vm.company.offers[i].isEditVisible;
        }
      }
    }
  }
   
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <div ng-repeat="offer in ctrl.company.offers">
      {{offer.name}}
      <button ng-click="ctrl.setEditVisibility(offer.id)">Toggle Edit Visibility</button>
      <span ng-if="offer.isEditVisible">{{offer.name}} Edit Details</span>
    </div>
  </div>
</div>

Post a Comment for "Ng-if Should Show Only One Object"