What is the best way to include auto complete values in a list?

<div class="maincontent">
    <div ng-app="autocompleteCustomTemplateDemo" ng-controller="DemoCtrl as ctrl" class="container container1">
        <div class="row">
            <div class="col-lg-12 col-sm-12">
                <h4><strong> Service</strong></h4>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <md-content layout-padding layout="column">
                    <form ng-submit="$event.preventDefault()">
                        <md-autocomplete ng-disabled="ctrl.isDisabled" md-no-cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-search-text- change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-selected-item-change="ctrl.selectedItemChange(item)"
                        md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.product_name" md-min-length="0" placeholder="Pick an Angular repository" md-menu-class="autocomplete-custom-template">
                            <md-item-template>
                                <span class="item-title">
                            <span> {{item.product_gid}} </span>
                                </span>
                                <span class="item-metadata" ng-model="g1" ng-click="type(g1)">
                            <span>
                            <strong>{{item.product_name}}</strong>
                            </span>
                                </span>
                            </md-item-template>
                        </md-autocomplete>
                        <div class="row">
                            <div class="col-md-12 text-right">
                                <md-button ng-click="add()">ADD</md-button>
                            </div>
                        </div>
                        <br/>
                        <div class="row table-responsive" ng-show="show_servicelist">
                            <div class="col-md-12 col-lg-12 col-sm-12">
                                <table class="table table-striped table-bordered table-condensed table-hover md-primary" md-progress="deferred">
                                    <thead class="header">
                                        <tr style="text-align:center">
                                            <th>S No</th>
                                            <th>product name</th>
                                            <th>Quantity</th>
                                            <th style="text-align:center">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr ng-repeat="service in services">
                                            <td>{{$index + 1}}</td>
                                            <td>{{service.product_name}}</td>
                                            <td><input type="text" ng-model="service.quantity" /></td>
                                            <td><input type="text" ng-model="service.amount" /></td>
                                        </tr>
                                    </tbody>
                                </table>
                                <div class="row">
                                    <div class="col-md-12 text-right">
                                        <md-button>Submit</md-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </md-content>
            </div>
        </div>
    </div>
</div>

JS

(function() {
    'use strict';
    angular
        .module('autocompleteCustomTemplateDemo', ['ngMaterial'])
        .controller('DemoCtrl', DemoCtrl);

    function DemoCtrl($timeout, $q, $log, $scope) {
        var self = this;
        $scope.services = [];
        
        $scope.add = function() {
            $scope.show_servicelist = true;
            $scope.services.push({
                product_name: self.selectedItem.product_name,
                quantity: "",
                amount: ""
            });
        };
        
        self.simulateQuery = false;
        self.isDisabled = false;

        self.repos = loadAll();
        self.querySearch = querySearch;
        self.selectedItemChange = selectedItemChange;
        self.searchTextChange = searchTextChange;


        function querySearch(query) {
            var results = query ? self.repos.filter(createFilterFor(query)) : self.repos,
                deferred;
            if (self.simulateQuery) {
                deferred = $q.defer();
                $timeout(function() {
                    deferred.resolve(results);
                }, Math.random() * 1000, false);
                return deferred.promise;
            } else {
                return results;
            }
        }

        function searchTextChange(text) {
            $log.info('Text changed to ' + text);
        }

        function selectedItemChange(item) {
            $log.info('Item changed to ' + JSON.stringify(item));
        }


        function loadAll() {
            var repos = [{
                    'product_gid': '1',

                    'product_name': 'stabilizer',
                    'forks': '16,175',
                }, {
                    'product_gid': '2',

                    'product_name': 'stand',
                    'forks': '760',
                }, {
                    'product_gid': '3',

                    'product_name': 'ac',
                    'forks': '1,241',
                },

            ];
            return repos.map(function(repo) {
                repo.value = repo.product_name.toLowerCase();
                return repo;
            });
        }


        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(item) {
                return (item.value.indexOf(lowercaseQuery) === 0);
            };

        }
    }
})();

I'm running the following code to display the value in the autocomplete after selecting the add button. I need the value to list one after another after clicking the add button. I have used a material for this. please guide me, and modify the code. The above code just displays the list empty, how to store a value in the list and allocate in order.

Answer №1

I have made modifications to 2 functions for you, they are expected to work correctly now.

The first step is to globally create the array.

self.repos = [{
        'product_gid': '1',
        'product_name': 'stabilizer',
        'forks': '16,175',
    }, {
        'product_gid': '2',
        'product_name': 'stand',
        'forks': '760',
    }, {
        'product_gid': '3',
        'product_name': 'ac',
        'forks': '1,241',
    },
];

function loadAll() {

    return self.repos.map(function(repo) {
        repo.value = repo.product_name.toLowerCase();
        return repo;
    });
}

add(object) {
    self.repos.push(object);
    self.loadAll();
}

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

Separate the paragraph within an HTML string and eliminate any paragraph that is empty

I need help splitting a string of HTML into an array list, with the condition that the paragraphs should not be empty. Each paragraph should contain some normal text, and if it only contains HTML text without any normal text like: <htmltag>&nbsp; ...

Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external var ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Having trouble incorporating a class with if and else statements, the code isn't functioning as expected

I am attempting to apply a class with an if-else statement, but for some reason it is not progressing past the if condition and reaching the else block. $('.headings aside').click(function() { if ($(this).children('span').hasClass( ...

Placing the Cloud Icon at the Center Right of the Navigation Border Background

I am in the process of creating a vertical navigation bar and I have the intention to include a cloud icon that is centered at the right border, positioned directly on the background line. <nav> <ul> <li><a href="#"> ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Identifying Image Requests Generated Dynamically in Javascript: A Guide

Essentially, my current setup involves utilizing a JavaScript Library that includes the following code within a function: var img = new Image(); // Creating a new img element img.src = 'URL/myImage.png'; // Setting the source path This result ...

The JSON syntax contains an unexpected token

I am encountering an issue with a JavaScript variable named "text" that contains the following value: text={"text":"@RT #Olle_Carly Nuevas filtraciones del iPhone 6: así sería comparado con el Samsung Galaxy S5 y el iPhone 5S: Des... http://t.co/eRuXLS6 ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...

Accessing router parameters in Vuex actions

Is there a more efficient way to pass router params into Vuex actions for a large form? edit_sport_type({ rootState, state, commit }, event) { const sportName = rootState.route.params.sportName <------- const payload = {sportName, event} ...

Displaying information obtained from other sources

Is there a way to extract data from websites without APIs and display it on my own website using JavaScript and React? I am looking to showcase information from multiple websites on my own site, but unfortunately these websites do not have public APIs. Ho ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

What are the best practices for creating responsive Iframes in videos?

I have been attempting to create a responsive video iframe, but unfortunately, I am facing some difficulties in achieving this. So far, the iframe works fine without any background frame. .embed-container { position: relative; padding-bottom: 56.25% ...

"Adjusting the background color based on the current day using PHP and CSS

Check out the screenshot of my result here. I'm currently experiencing an issue with the code while trying to modify a calendar. The error seems to be originating from tablerow.php, as I've indicated in the comments. I am attempting to change the ...

The count of records in MongoDB by the current month

Recently delving into MongoDB, I found myself in need of a way to retrieve the count of posts made in the current month. Keeping timestamps true in my PlateModel model, it appears as follows: { timestamps: true } The current code snippet in my Controller ...

Converting a multi-dimensional array to a single array in JavaScript: the ultimate guide!

I have encountered a scenario in my application where there is an array with multiple arrays nested inside: https://i.sstatic.net/3uHP9.png I am looking to transform this structure: [ { "tag": [ { "key": "asda ...

Refresh outfit designs or retrieve information from fragment shader post-processing

While working on image processing in the fragment shader (specifically thresholding), I find myself wanting to access the processed result from JavaScript so that I can save the modified image using standard JavaScript methods. I send the original texture ...

Express handlers with ES6 harmony arrow functions

Should arrows be preferred over regular function expressions in expressjs middleware handlers? app.use(mountSomething()) router.use(mountSomethingElse()) app.get('/', (req, res, next) => { next(); }) route.get('/path', (req, ...

React components may overlap each other due to their elements intersecting

I am currently facing an issue in my React project where the footer is overlapping with the elements at the bottom of the page. To view the live project, you can visit: Although I have researched similar questions on this topic and tried adjusting margin ...

Switch the asp.net form view to insert mode using a different webpage

My ASP.NET project consists of two pages developed in ASP.NET Web Forms. The first page displays a Main Grid View Control, while the second page contains details within a Form View control. Within Page 1, there is a button that, when clicked, should chang ...