1

I am trying to hide the div if any of the buttons in the ng-repeat is clicked. However it doesn't seem to work, it leads me to think if ng-hide or ng-show won't work if it is controlled from within a ng-repeat?

<div data-ng-hide="showChooseHardware">
    <table class="table">
        <tbody>
            <tr data-ng-repeat="hardware in hardwares">
                <td>{{hardware.name}}</td>
                <td>
                    <button type="button" class="btn" data-ng-click="showChooseHardware=!showChooseHardware"/>
                </td>
            </tr>
        </tbody>
    </table>
</div>
Oh Chin Boon
  • 22,288
  • 48
  • 139
  • 212

2 Answers2

2

This is due to the fact that ng-repeat creates a new scope for each template and due to how prototypal inheritance works in JavaScript (and AngularJS).

Use an object:

$scope.viewModel = { showChooseHardware: false };

HTML:

data-ng-hide="viewModel.showChooseHardware"

And:

data-ng-click="viewModel.showChooseHardware=!viewModel.showChooseHardware"

A great explanation on the issue can be found here.

I recommend using ng-showinstead in this case since the variable is called showChooseHardware.

Community
  • 1
  • 1
tasseKATT
  • 38,330
  • 8
  • 83
  • 65
  • Thanks, your explanation works. Reason why i used showChooseHardware with ng-hide was due to debugging, i was trying out both ng-show and ng-hide to see if ng-show was a problem. I reverted back to ng-show now. Now, i need to read the referenced link.. TY! – Oh Chin Boon Feb 01 '15 at 17:21
  • A simple and effective way to avoid scope inheritance issues is to use controllerAs syntax. `ng-controller="MyController as ctrl" ng-model="ctrl.showChooseHardware"` – André Werlang Feb 01 '15 at 18:43
1

ngRepeat directive creates new scope in every iteration,for every item in array.It can make a problem,which you have.

Hazarapet Tunanyan
  • 2,691
  • 25
  • 27