Trouble with AngularJS ng-repeat filter when using input and ng-model

In my AngularJS project, I am using ng-repeat to display a list and want to implement a filter that shows only items containing the user-input value. I tried setting it up following an example from here, but it didn't work as expected.

Here is the HTML code:

<div ng-if="result.length > 0">
    <input type="text" class="pl-4" ng-model="searchText" placeholder="Search" />

    <div class="mt-4 text-left animationIf" ng-repeat="item in result | filter: searchText">
        <div>
            <span class="text-danger">Name: </span>
            <span class="m-0" ng-bind="item.name"></span>
        </div>
        <div>
            <span class="text-danger">Country: </span>
            <span class="m-0" ng-bind="item.country"></span>
        </div>
        <div>
            <span class="text-danger">Born: </span>
            <span class="m-0" ng-bind="item.born"></span>
        </div>
        <div>
            <span class="text-danger">Surname: </span>
            <span class="m-0" ng-bind="item.surname"></span>
        </div>
    </div>
</div>

An example of the 'result' object looks like this:

$scope.result = [{
    name: "John",
    country: "California ",
    born: "283 AC",
    surname: "Snow"
},{
    name: "Michael",
    country: "US",
    born: "1958",
    surname: "Jackson"
}];

When I initialize with ng-init="$scope.result = 'John'", the filter works for 'John', but if I change the input value to 'Michael', no filtering occurs. What am I missing here?

Answer №1

let myApp = angular.module('sampleApp',[]);
myApp.controller('sampleCtrl',function($scope){
$scope.data = [{
    name: "Alice",
    country: "New York",
    born: "1992",
    surname: "Smith"
},{
    name: "Bob",
    country: "Canada",
    born: "1975",
    surname: "Johnson"
}];

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input type="text" class="pl-4" ng-model="searchText" placeholder="Search" />
<body ng-app="sampleApp" ng-controller="sampleCtrl">
 <div class="mt-4 text-left animationIf" ng-repeat="item in data | filter: searchText">
    <div>
        <span class="text-danger">Name: </span>
        <span class="m-0" ng-bind="item.name"></span>
    </div>
    <div>
        <span class="text-danger">Country: </span>
        <span class="m-0" ng-bind="item.country"></span>
    </div>
    <div>
        <span class="text-danger">Born: </span>
        <span class="m-0" ng-bind="item.born"></span>
    </div>
    <div>
        <span class="text-danger">Surnname: </span>
        <span class="m-0" ng-bind="item.surname"></span>
    </div>
</div>

Answer №2

Your solution is effective as it stands. The problem arises in the NgInit section where you are assigning the scope object result to only "John", which is not an array and will not work with NgRepeat out-of-the-box.

Therefore, simply avoid setting $scope.result = 'John' and everything should function correctly

angular.module("app",[])
.controller("myCtrl", function($scope){
$scope.result = [{
    name: "John",
    country: "California ",
    born: "283 AC",
    surname: "Snow"
},{
    name: "Michael",
    country: "US",
    born: "1958",
    surname: "Jackson"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
<input type="text" class="pl-4" ng-model="searchText" placeholder="Search" />

<div class="mt-4 text-left animationIf" ng-repeat="item in result | filter: searchText">
    <div>
        <span class="text-danger">Name: </span>
        <span class="m-0" ng-bind="item.name"></span>
    </div>
    <div>
        <span class="text-danger">Country: </span>
        <span class="m-0" ng-bind="item.country"></span>
    </div>
    <div>
        <span class="text-danger">Born: </span>
        <span class="m-0" ng-bind="item.born"></span>
    </div>
    <div>
        <span class="text-danger">Surnname: </span>
        <span class="m-0" ng-bind="item.surname"></span>
    </div>
</div>
</div>

Answer №3

Your code looks fine to me. However, it's best to avoid using the ng-init directive as you pointed out:

ng-init="$scope.result = 'John'"

This directive can potentially clear the array that you've set up in your controller.

Answer №4

Initially, I included an outer DIV that contained ng-if="result.length > 0" to ensure it would only display when the results were populated. Unfortunately, this caused the input functionality to cease completely.

However, after replacing the ng-if with ng-show, my issue was successfully resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery Mobile dual range slider functioning but experiencing some glitches

I successfully created a dual range slider by stacking two sliders on top of each other using the jQuery Mobile framework. In addition, I have implemented JavaScript to ensure that the left thumb does not exceed the right one. However, I have encountered ...

While I believed that my template's if/else/endif logic would resolve the issue, I encountered a NoReverseMatch error when trying to access /

I received an error message as follows: NoReverseMatch for 'grouplocation_add' with arguments '('',)' not found. 1 pattern(s) tried: [u'ipaswdb/grouplocations/add/(?P<pk>[0-9]+)/$'] After adding context[&apos ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

Troubleshooting the NestJS @InjectModel() dependency issue: Solutions and Fixes

userLink.api.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document, Types } from 'mongoose'; import { User } from 'src/users/schemas/users.schema'; export type UserLinkDocument = UserLink & ...

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

We encountered an error: Unable to access properties of an undefined variable (referencing 'onClicked')

I am currently in the process of converting my Chrome pure JS extension into a Vue.js version. The pure JS version works perfectly fine. However, when using Vue.js, I encounter an error that I can't seem to understand while loading the extension. Be ...

The issue of the cursor not showing up in Chrome within a nested contenteditable structure arises when applying CSS after the

Currently, I am coding a HTML document that includes an element with the attribute contenteditable set to true, but this element is wrapped inside a parent element with contenteditable set to false. The HTML structure looks like this: <div contentedita ...

Facing an issue with the format.js not functioning properly in Rails version 6.1.3

styles.css @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap"); body { font-family: 'Roboto', sans-serif; color: #333; } .wrapper { max-width: 960px; margin: 0 auto; } button { background ...

The functionality of an external Javascript library fails to operate properly once the website is deployed to a hosting

Encountering a peculiar bug with my website at . The website is supposed to load both the JQuery and EasyUI libraries. JQuery is loading correctly as a function to print out "ready" when the page loads. The issue arises when trying to drag products onto th ...

How to Easily Add GitHub NPM Packages to Your SAPUI5 Web IDE

Looking to integrate an NPM package from Github into SAPUI5 using the WebIde Framework. Package Link: https://github.com/commenthol/date-holidays/blob/master/README.md#usage Primary Issue: Need a file with the library for importing and copying into the W ...

Revamp the table layout for mobile with a unified markup structure

I want to customize the display of my bootstrap table for mobile view. Each row entry should be shown in a separate box or card, similar to the following examples: First: Mark Last : Otto Handle: @mdo Second card- First:Jacob Last:Thornton Handle:@fat Is ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

Implementing a feature in jQuery to reveal an element upon button click

I need to create a functionality where clicking a button will display a panel. Initially, I have set the panel's visibility to false in its properties. So, when the user clicks the button, the button should hide and the panel should show up. How can I ...

Retrieving the correct array from an SQL table using PHP and SQL

I have a table stored in a database that looks like this: - ID | successor - 01 | 02 - 01 | 04 - 01 | 08 - 02 | 03 - 04 | 05 - 05 | 06 This table serves as a simple assignment table for a module in an E-Learning system. The current PHP code I am using i ...

Retrieve the json translation file from the server using Angular and seamlessly integrate it into the browser

I recently obtained a JSON file from the server that contains translations for handling server error messages in my frontend application. I am wondering if it would be feasible to replace an existing empty JSON file in my app with this new file, or if it ...

Automatically Resizing an iFrame Height Upon Submit Button Click

Currently, I am facing an issue with a form that generates an iFrame for the Payment section. While the height of the iFrame is set correctly, whenever there are errors in the form submission and error messages appear, they push the submit button below t ...

Utilizing Electron and jQuery to incorporate a loading animated GIF into a newly opened window, where the animation pauses

I am working on an electron project that involves opening a new window with an index.html file. In this newly opened window, I have included an animated.gif in the body section. <!doctype html> <html lang="en> <head> <meta charset ...

Allow users to edit MediaWiki sandbox pages without needing to log in

I am looking to allow editing on a sandbox page of a wiki website I manage. I want this specific page to be editable with just a keypress or a button, while all other pages would require a login. The goal is to make it easier for new visitors to understand ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...