Implementing ng-if Filtering Based on String Contains Condition in AngularJS

Nov 26, 2025 · Programming · 10 views · 7.8

Keywords: AngularJS | ng-if directive | string contains detection

Abstract: This technical article provides an in-depth exploration of implementing string contains condition filtering using the ng-if directive in AngularJS framework. By analyzing the principles, syntax differences, and browser compatibility of two core methods - String.prototype.includes() and String.prototype.indexOf(), it details how to achieve precise conditional rendering in dynamic data scenarios. The article compares the advantages and disadvantages of ES2015 features versus traditional approaches through concrete code examples, and offers complete Polyfill solutions to handle string matching requirements across various browser environments.

Technical Background of String Contains Detection

In modern web development, dynamic data filtering represents a core functionality of frontend frameworks. AngularJS, as a popular MVVM framework, provides powerful data binding and conditional rendering capabilities through its directive system. The ng-if directive specifically enables dynamic control over DOM element visibility based on expression truth values, which proves particularly crucial when handling dynamic data lists.

Deep Analysis of Core Methods

ES2015 String.prototype.includes() Method

The ES2015 standard introduced the String.prototype.includes() method, specifically designed to detect whether a string contains a specified substring. Its syntax structure is: str.includes(searchString[, position]), where searchString represents the substring to search for, and position is an optional starting position for the search.

The specific implementation example in AngularJS templates appears as:

<li ng-repeat="select in Items" ng-if="select.name.includes('?')">
    <foo ng-repeat="newin select.values">
        {{new.label}}
    </foo>
</li>

This method returns a boolean value - true when the substring exists, and false when it doesn't, perfectly aligning with the logical requirements of the ng-if directive.

Traditional String.prototype.indexOf() Method

Prior to ES2015, String.prototype.indexOf() served as the standard method for implementing string contains detection. This method returns the index position of the first occurrence of the specified substring within the original string, or -1 if not found.

Its working principle relies on character position indexing:

ng-if="select.name.indexOf('?') > -1"

When the return value exceeds -1, it indicates the target character exists; when equal to -1, it signifies absence. This approach maintains excellent compatibility across all modern browsers.

Browser Compatibility and Polyfill Solutions

Although the includes() method offers more concise and intuitive syntax, its browser support presents limitations. Internet Explorer and early versions of Opera browsers lack support for this method. To ensure cross-browser compatibility, consider implementing the following Polyfill solution:

if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
        'use strict';
        if (typeof start !== 'number') {
            start = 0;
        }
        if (start + search.length > this.length) {
            return false;
        } else {
            return this.indexOf(search, start) !== -1;
        }
    };
}

This code first detects whether the current environment supports the includes method, and if not, implements equivalent functionality based on indexOf, ensuring proper operation across different browser environments.

Syntax Differences in Angular Version Evolution

In Angular(2+) versions, directive syntax undergoes changes while maintaining consistent core logic:

<li *ngFor="let select of Items" *ngIf="select.name.includes('?')">
    <foo *ngFor="let new of select.values">
        {{new.label}}
    </foo>
</li>

It's important to note that Angular(2+) utilizes *ngFor and *ngIf as structural directives, whose underlying implementation mechanisms differ from AngularJS's ng-repeat and ng-if, though the logical principles of string detection remain identical.

Practical Application Scenario Analysis

In the scenario described in the original problem, data formats resemble 88?77 - dynamic numerical values combined with fixed question mark characters. Using string contains detection enables precise filtering of data items containing specific characters. This method proves particularly suitable for:

Through appropriate string detection logic, developers can construct more intelligent and user-friendly interactive interfaces.

Performance Optimization Recommendations

When processing large-scale data lists, string detection operations may become performance bottlenecks. Recommendations include:

  1. Completing string detection during data preprocessing stages
  2. Implementing caching mechanisms to avoid repeated calculations
  3. Considering Web Workers for intensive string operations
  4. Appropriately using Angular's track by for list rendering optimization

These optimization measures can significantly enhance overall application performance and user experience.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.