Ng-if should only show one object

Hello 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 works fine, the problem is that it displays the oi-offer-edit directive for every duplicate object. If you need more information, please feel free to ask!

0
source share
3 answers

If you do not want to touch the markup and want the element to be oi-offer-editrepeated, you need to use the boolean property in the object itself offer:

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

The solution, before I realized that you want to have this directive in each md-card:

, oi-offer-edit ng-repeat, , , offer - company.offers.

, offer oi-offer-edit . - :

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

, ng-repeat.

0

oi-offer-edit , , ng-if, .

, , .

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>
Hide result
0

Source: https://habr.com/ru/post/1654289/


All Articles