What is the best way to filter an array in Angular?

When I type in the input field, only the list items containing my input will be displayed in the unordered list. For example, if I type "Ad", then only the list item with "Add some todos" will be shown. When I clear the input, all the list items will reappear. How can I achieve this?

Here is the code:

<body>
<script src="angular.js"></script>
<div ng-controller="ctr1">
    <input ng-model='newTodo' type="text" ng-keyup="$event.keyCode == 13 && addTodo()">
    <ul>
        <li ng-repeat="todo in fillArray">
            <span>{{todo.text}}</span>
            <button ng-click="removeTodo($index)">X</button>
        </li>
    </ul>
</div>
<script>

    var app = angular.module("app",[]);
    var contrl = app.controller('ctr1',['$scope',function ($scope) {
        $scope.todos = [{text:"Add some todos"}];
        $scope.newTodo = '';
        $scope.addTodo = function () {
            var text = this.newTodo.trim();
            if(text){
                this.todos.push(
                        {text:text}
                );
                this.newTodo= '';
            }
        };
        $scope.removeTodo = function (index) {
            this.todos.splice(index,1);
        };

        $scope.fillArray =$scope.todos.filter(function (item) {
            return (item.text.toLocaleLowerCase().indexOf($scope.newTodo) > -1);});
    }]);

</script>
</body>

**How do I populate the fillArray? ** My current approach seems to be incorrect.

Answer №1

<body>
<div ng-controller="ctr1">
    <input ng-model='newTodo' type="text" ng-keyup="$event.keyCode == 13 && addTodo()">
    <ul>
        <li ng-repeat="todo in todos | filter : newTodo">
            <span>{{todo.text}}</span>
            <button ng-click="removeTodo($index)">X</button>
        </li>
    </ul>
</div>
<script>

    var app = angular.module("app",[]);
    var contrl = app.controller('ctr1',['$scope',function ($scope) {
        $scope.todos = [{text:"Start creating your todo list"}];
        $scope.newTodo = '';
        $scope.addTodo = function () {
            var text = this.newTodo.trim();
            if(text){
                this.todos.push(
                        {text:text}
                );
                this.newTodo= '';
            }
        };
        $scope.removeTodo = function (index) {
            this.todos.splice(index,1);
        };


    }]);

</script>
</body>

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

Attempted to simultaneously initialize angular multiple times using express 4

Every time I attempt to load an Angular route and template, I encounter the following error message: WARNING: Attempting to load angular multiple times. I suspect there is a routing issue leading to an infinite loop but pinpointing the source of the prob ...

Alert: The `className` property did not align and there is an absence of the window within the Next 13 App Router

I've been struggling to fix an error in the Next.js 13 App Router. Warning: Prop `className` did not match. Server: "styled__HeadLink-sc-6589f63-0 fIOFTm" Client: "styled__HeadLink-sc-b76127ed-0 jzAIeh" I've spent a lot of ...

How to implement 'cancel changes' feature in AngularJS with the use of splice method

In my datagrid, I am displaying data from an array called listOfAttributes. Each row has an edit icon which, when clicked, reveals two buttons: save and cancel edit. The issue I am facing is that when a user clicks on cancel edit, the updated data should ...

Creating an adaptable grid system in Vue Material

I am working on a project where I am using Vue-Material to display user-inputted cards in a grid layout. While the cards are rendering correctly, I want to optimize the grid to make it flexible, justify the cards, and stagger them in a way that eliminates ...

trigger a function when the iframe is altered

I am currently working on creating a function that can process credit card payments using an iframe. The challenge I am facing at the moment is dealing with error messages appearing in a less than ideal manner. Photo: I have been attempting to capture the ...

Is there a way to send a variable from a client-side script to a server-side script?

I am facing a challenge in Google App Maker where I am attempting to execute a Client Script to retrieve a variable and then pass that variable to a Server Script for further use. However, I am struggling to figure out the correct implementation. Within m ...

Accessing the req object in Node.js using Express

Currently, I am attempting to redefine the function send in order to include an express-session value with each response. Unfortunately, I seem to be encountering issues accessing the variable req within the definition of send. 01| let app = express(); 02| ...

Is there a way to assign a sessionStorage key by clicking on certain elements in HTML?

I have encountered an issue while attempting to set a value in the sessionStorage. The problem lies in storing the sessionStorage "key" differently based on the item clicked. For instance, if I click on the first view chat, I should store a key of "1", and ...

Is Node.js categorized as multithreading due to its utilization of worker threads?

Throughout my life, I was under the impression that Node.js and JavaScript operated as a single threaded language. It was always said that Node.js wasn't ideal for CPU intensive tasks due to its single threaded nature. Multithreading, on the other han ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Issue with ngFor in Angular 2 causing error message in console

I'm currently following a guide to create a basic page that showcases different courses. However, I've encountered an error while testing the code in the console. The Angular 2 dependency is listed as "angular2": "2.0.0-beta.7". I have also attem ...

What could be causing this image to disregard the designated width value?

https://i.stack.imgur.com/bPH4t.png While working on my project with Next.js, I encountered an issue with the IconText component provided by Next.js. Even though I specified a width value for the image, it seems to be ignoring it. Below is the structure o ...

Display event using Angular

I am currently working on an Angular project where I need to print a specific area of the page. While I know that this can be done using media CSS, it is causing issues for me due to the numerous print functionalities present in the project. I am attemptin ...

Rendering issue with component

I am encountered with a situation where one component is failing to render its sub-component. Surprisingly, there are no visible errors in the console. The data I'm expecting from the web call is also coming through without any issues. However, for so ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

Steps to activate a particular Bootstrap tab upon clicking a hyperlink

Trying to implement a Bootstrap tab panel in the following manner: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href ...

Using Angular ui.bootstrap tabs along with ui.router: a step-by-step guide

My initial approach to using ui.bootstrap tabs with ui.router is as follows: <tabset> <tab heading="Tab1" select="$state.go('home.tab1')"> <div ui-view="forTab1"></div> </tab> <tab heading="Tab2" select ...

What is the method of showing a leaflet map in a particular div tag?

I want to showcase a leaflet map, but I specifically need it to be displayed in a div tag with a particular id like document.getElementById("map"). Here is the code snippet below which utilizes Vue.js: Here is the div tag where the map will be rendered: ...

Troubleshooting a minor JavaScript loop problem

I am facing an issue with my script that retrieves data from a database. Currently, when the search() function is called by clicking a button, only one result is displayed in a new div. How can I ensure that a new div is created for each result found, rath ...

`Why setRequestHeader is essential for Ajax and XMLHttpRequest`

Should I ever manually specify the setRequestHeader as 'application/x-www-form-urlencoded' for an ajax POST request? Is it necessary to manually define the setRequestHeader as 'multipart/form-data' when uploading files via ajax? Do XMLH ...