Dan Gilberstadt
Dan Gilberstadt

Reputation: 95

Angular: Preventing Display of Directives Until User Types in Search Bar

I'm working with Angular to display a list of users with roles on the page, and allow filtering based on email address. This is working well, but Angular adds a lot of DOM elements and watchers, which is slowing down the page a lot. To prevent this issue, I'm trying to only show the users when text is entered into a search field.

Here's the code for the search box and the ng-repeat creating the user directives:

<!-- Search -->
<h3 class="heading">Showing<span ng-show="searchUsers.length"> {{filteredUsers.length}} of</span> {{users.length}} Users</h3>
<div id="search_users_container">
    <input type="search" name="search_users" id="search_users" placeholder="Search all users" ng-model="searchUsers" ng-value="" />
</div>
<!-- /Search -->

<!-- Users -->
<section id="users" class="cards masonry" ng-show="!searchUsers.length || filteredUsers.length" masonry="true" data-images-loaded="true">
    <!-- User Cards -->
    <user-card ng-model="user" ng-repeat="user in filteredUsers = (users | filter: { Email: searchUsers })" ng-show="searchUsers.length && filteredUsers.length"></user-card>
    <!-- /User Cards -->
</section>
<!-- /Users -->

The users hidden until you type in the search bar, but it only visually hides the users with the ng-show, but they still add them to the DOM (I can see when when inspecting in Chrome dev tools) and watchers are still added.

When I type in the search bar, the users are filtered correctly, the non-matching users are removed from the DOM and the number of watchers are reduced, which is good.

What I'd like to do is prevent Angular from adding the users to the DOM until I type in the search field.

Does anyone have any suggestions on the best way to do this?

Upvotes: 0

Views: 67

Answers (1)

Anthony
Anthony

Reputation: 1827

Use ng-if instead of ng-show. That will remove elements from the DOM rather than not display them.

Upvotes: 1

Related Questions