ng-if应该只显示一个对象

时间:2016-09-11 18:00:09

标签: javascript html angularjs

亲爱的Stackoverflow社区我有一个问题。首先是我的代码:

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>

我的控制器:

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

它工作得很好问题是它为每个重复的对象显示了oi-offer-edit指令。 如果您需要更多信息请不要犹豫!

3 个答案:

答案 0 :(得分:0)

这是因为你已经限制了每个ng-repeat对象。

答案 1 :(得分:0)

如果您不想触摸标记并希望重复oi-offer-edit元素,则必须在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>

解决方案之前我意识到,您希望在每个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;
}

答案 2 :(得分:0)

如果您想独立于每个商品对象切换oi-offer-edit的可见性,那么您应该将您在ng-if指令中检查的布尔标志移动到商品数组中。

检查以下示例,它将帮助您完成您想要做的事情。

&#13;
&#13;
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;
        }
      }
    }
  }
   
&#13;
<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>
&#13;
&#13;
&#13;