简体   繁体   中英

How to hide button in ng-repeat in AngularJS?

My View:

<div class="col-sm-4 col-xs-4" ng-repeat="(id, object) in objects">
    <button type="primary" 
        ng-click="add(id)"  
        ng-hide="id.plz" style="color: cyan;">Add</button>
</div>

Controller JavaScript:

$scope.add = function(id){
   // some function;
   $scope.objects[id].plz = true;
}

Any idea why it won't work?

<div class="col-sm-4 col-xs-4" ng-repeat="(id, object) in objects">

<button type="primary" ng-hide="objects[id].plz" ng-click="add(id)"   style="color: cyan;" >Add</button>

<div>

here in ng-hide="id.plz" id is the index so there is no id.plz

learn more about ng-hide and alternatives here

If you want to conditionally hide your button in ng-repeat, use ng-hide, ng-show(if there is a chance that you will hide and show it later) or ng-if(if it's a one time hide of button).

ng-hide takes a boolean and shows/displays accordingly. In your case your ng-hide is always turned out to be true, so you are unable to hide. Just write the condition required in your ng-hide to hide your button

Hide the button when its clicked like in this fiddle :

View

<div ng-controller="MyCtrl">
    <div ng-repeat="user in data">
      {{ user.name}}
      <button ng-hide="hide[$index]" ng-click="add();hide[$index] = true;">
        Add
      </button>
    </div>
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {

    $scope.add = function () {
      console.log('add');
    }

    $scope.data = [{
      name: 'frank'
    },{
      name: 'peter'
    },{
      name: 'melanie'
    },{
      name: 'sven'
    },{
      name: 'basti'
    },{
      name: 'edjuh'
    }];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM