How to use ng-change and custom function In Angular
- In this approach, we have used the ng-change directive that is used to detect changes in the input field and execute the “processInput” function.
- When a user enters a comma-separated list in the input field, this function splits the input into individual items, trims any extra whitespace, and filters out empty items.
- The resulting list of items is displayed in an unordered list.
Example: Below is an example that demonstrates the use of commas as a list separator in AngularJS using ng-change and custom JavaScript functions.
HTML
<!DOCTYPE html> < html ng-app = "listApp" > < head > < script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js" > </ script > < style > body { font-family: Arial, sans-serif; text-align: center; } h1 { color: green; } #itemInput { width: 60%; padding: 10px; margin: 10px; font-size: 16px; } ul { list-style-type: none; padding: 0; } ul li { background-color: #f0f0f0; margin: 5px; padding: 10px; border-radius: 5px; } button { background-color: red; color: white; border: none; padding: 10px 20px; margin: 10px; cursor: pointer; } </ style > </ head > < body ng-controller = "ListController" > < h1 >w3wiki</ h1 > < h3 > Approach 2: Using ng-change and custom JavaScript function </ h3 > < label for = "itemInput" > Enter items (comma-separated): </ label > < input type = "text" id = "itemInput" ng-model = "itemInput" ng-change = "processInput()" placeholder = "E.g., Geeks, Article, AngularJS" > < p >Items entered:</ p > < ul > < li ng-repeat = "(index, item) in itemList" > {{ index + 1 }}. {{ item }} </ li > </ ul > < script > var app = angular.module('listApp', []); app.controller('ListController', function ($scope) { $scope.itemInput = ""; $scope.itemList = []; $scope.processInput = function () { var items = $scope.itemInput.split(',').map(function (item) { return item.trim(); }); items = items.filter(function (item) { return item !== ''; }); $scope.itemList = items; var duplicates = findDuplicates(items); if (duplicates.length > 0) { alert("Duplicate items detected: " + duplicates.join(", ")); } }; function findDuplicates(arr) { return arr.filter((item, index) => arr.indexOf(item) !== index); } }); </ script > </ body > </ html > |
Output:
How to use comma as list separator in AngularJS ?
In this article, we will use commas as a list separator in AngularJS applications.
In AngularJS, we can use a list separator by simply placing the command between the items in the list. If we have an array of items that we need to display in the application, then we can use ng-repeat to iterate through this array and then display each item which is separated through the comma. So, here we will see 2 different approaches with their implementation.