UX Guy
UX Guy

Reputation: 257

How would I ng-show an item if another DOM is visible?

Would I just add ng-model to the visible/invisible DOM and then ng-show="thatElement.visiblity==='true'"?

<span>Show this text when the div is visible</span>
<div ng-repeat="user in users" ng-show="user.section===radio.model">{{user.name}}</div>

Update: If I put the Show this text when the div is visible, it's going to repeat for every user in users.

Upvotes: 1

Views: 1105

Answers (1)

Shomz
Shomz

Reputation: 37701

You need to restructure it:

<div ng-repeat="user in users" ng-show="user.section===radio.model">
    <span>Show this text when the div is visible</span>
    <div>{{user.name}}</div>
</div>

Or, (since it wasn't clear), if you want the div to be shown all the time, and span only when the condition is met, you can do this:

<div ng-repeat="user in users">
    <span ng-show="user.section===radio.model">Show this text when the div is visible</span>
    <div>{{user.name}}</div>
</div>

You can also use a filter that will sort out the object that enter ng-repeat so you can avoid processing unneeded subobjects like that.


Here's a simple example using ng-if on the spans:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.users = [{
      name: 'Mr. Visible',
      visibility: true
    }, {
      name: 'Mr. Invisible',
      visibility: false
    }]
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="user in users">
    <span ng-if="user.visibility">Show this text when the div is visible</span>
    <div>{{user.name}}</div>
    <br />
  </div>
</div>


UPDATE

Example using a boolean to denote whether to show a single span:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.users = [{
      name: 'Mr. Visible',
      visibility: true
    }, {
      name: 'Mr. Invisible',
      visibility: false
    }];

    $scope.showSpan = false;
    for (var i in $scope.users) {
      if ($scope.users[i].visibility) {
        $scope.showSpan = true;
        break;
      }
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <span ng-show="showSpan">Show this text when the div is visible</span>
  <div ng-repeat="user in users">
    <div>{{user.name}}</div>
    <br />
  </div>
</div>

Upvotes: 1

Related Questions