Utilizing AutoComplete functionality in AngularJS with ngTagsInput

Using ngTagsInput in my project for tagging has posed a problem. After implementing the loadTags function to fetch data from an API and changing the structure to {text : sometag}, I encountered an issue where the autocomplete tag feature stopped working. I followed a tutorial at but still faced this issue.

Struggling with LoadTags Data Retrieval from API

$scope.loadTags = function(query) {
    var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
    data = {
        username: "newshubid",
        data: {
            orderby: {
                field: "label",
                type: "DESC"
            }
        }
    };
    args = {
        "data": JSON.stringify(data)
    };
    param = $.param(args);
    HttpService("POST", url, param, function(response) {
        res = angular.fromJson(response.data);
        angular.forEach(res, function(item) {
            $scope.get_cat = {
                text: item.label
            };
            return $scope.get_cat;
        });
    });
};

HTML Implementation

<tags-input ng-model="tag" class="bootstrap"
                                        replace-spaces-with-dashes="false"
                                        on-tag-added="AttachTag($tag)"
                                        on-tag-removed="RemovedTag($tag)">
        <auto-complete source="loadTags($query)"></auto-complete>
</tags-input>

If you have any insights on how to fix this issue or spot where I might have made a mistake, please share your thoughts. Thank you!

Answer №1

You've mistakenly utilized the incorrect ng-model binding for the tag data

To rectify this, consider defining $scope.get_cat as an array and pushing each tag into it.

$scope.loadTags = function(query) {
    var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
    data = {
        username: "newshubid",
        data: {
            orderby: {
                field: "label",
                type: "DESC"
            }
        }
    };
    args = {
        "data": JSON.stringify(data)
    };
    param = $.param(args);
    HttpService("POST", url, param, function(response) {
        res = angular.fromJson(response.data);
        $scope.get_cat = []
        angular.forEach(res, function(item) {
            $scope.get_cat.push({
                text: item.label
            });

        });
        return $scope.get_cat;
    });
};

Answer №2

After carefully reviewing the ngTagsInput documentation, it is clear that a promise must be returned. I have made some adjustments to your code for you. The Angular $q service handles promises in this case. Make sure to inject $q into your controller to make it work.

$scope.loadTags = function(query) {
        var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
        data = {
            username: "newshubid",
            data: {
                orderby: {
                    field: "label",
                    type: "DESC"
                }
            }
        };
        args = {
            "data": JSON.stringify(data)
        };
        param = $.param(args);
        var deferred = $q.defer();
        HttpService("POST", url, param,
        function(response) {
            res = angular.fromJson(response.data);
            $scope.get_cat = []
            angular.forEach(res, function(item) {
                $scope.get_cat.push({
                    text: item.label
                });

            });
              deferred.resolve($scope.get_cat);
              return deferred.promise; 
        });
    };

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

Transitioning from Webpack version 4 to version 5 resulted in a failure to detect certain styles

After migrating my React project to Webpack v5, I am facing an issue where none of my .scss files are being picked up when I run the project. I meticulously followed the guide on migrating webpack https://webpack.js.org/migrate/5/, updated all plugins and ...

How can I restrict the number of characters per line in a textarea using javascript or jQuery?

Is there a method to control the number of characters per line in a textarea? For example, on lines 1-3 of the textarea, only 20 characters can be entered, while on subsequent lines, up to 50 characters are allowed. The current structure of the textarea l ...

Dynamic banner featuring animated text, automatically resizing divs based on width while maintaining body width

Currently, I am working on creating a banner with moving text. While I have managed to come up with a solution for implementing this effect, there are two significant issues that I am facing. The width values in pixels need to be manually adjusted based ...

The lightbox is triggered by clicking on a different div to display its content

Great news - my lightbox is up and running! Each image on my website corresponds to a different organization, and clicking on the image opens a specific lightbox. My question is: how can I have a lightbox configured so that only the trigger image is displ ...

Loading JS and CSS files in relation to the website root directory

When it comes to including CSS/JS files, what are the best practices for defining the file URI? Some people prefer to include files relative to the website root by specifying the full URI: <link rel="stylesheet" href="/my/path/to/css/main.css"> Thi ...

Checking for valid single values in an array

I am handling an array in my project where values are either true or false. For this task, I am utilizing vuelidate. selectedDays: [ false, false, false, false, false, false, false ], In my templ ...

Creating an autocomplete/autosuggestion feature using AJAX and displaying the results in a table separate from the form

I am in the process of creating a basic webpage with a search engine. I have learned that to incorporate autocomplete/autosuggest with a form, using ajax is necessary. This is acceptable to me. There are numerous solutions available online, but unfortunate ...

JavaScript Calendar lacks two days

I'm currently developing a custom calendar application using Javascript with Vue JS. One of the methods I've created is for getting the number of days in a specific month: daysInYearMonth(y,m){ return new Date(y, m, 0).getDate() } When I log ...

Eliminate duplicate elements within arrays stored in an object using Javascript

My data consists of an array of objects, though I am unsure of the exact structure. However, it appears similar to this: list = { "ZIG": [ "CSK", "DKR", "CSK", "YNA", "CSK" ], "ZKG": [ "YNA" ], "ZND": [ "NIM", "DKR", ...

Importing a JSON file into a JavaScript script

let jsonData ; $.getJSON("../data.json",function(response){ jsonData = response; }); Despite using $.getJSON() from jQuery, I am consistently getting null data in return. The JSON file path is confirmed to be accurate, but the issue persists. ...

Why am I getting an error in Node's mongoose saying that the function is undefined?

I am currently in the process of developing a Node script that will establish a connection with an external server's MongoDB and add a new user. This is pretty basic stuff that I have encountered in numerous tutorials while using localhost. However, I ...

Is there a way to dynamically change the source of an image based on different screen sizes using Tailwind CSS?

Currently, I am utilizing the next/Image component for setting an image and applying styling through tailwindcss. However, I have encountered a roadblock at this juncture. My Objective My goal is to dynamically change the src attribute of the image based ...

Converting JSON into HTML has me completely baffled

Despite my best efforts, I have managed to navigate my way through the code thus far, but I am puzzled as to why the JSON data is not being sent to the HTML via JavaScript. I can manually input the necessary parts in the developer console after onLoad an ...

Creating Dynamic Menus with Material UI

I am currently working on rendering a Material UI Menu for each of my JSX Button Elements. However, all of my Menu Items are currently stacked on top of each other, and I want to be able to display only the Menu related to the clicked Button. Check out th ...

An error occurred during the extraction of nested JSON data in a SQL query

I have encountered an issue while running an SQL query to extract nested JSON data. SELECT watsonResponse.responseId, watsonResponse.chatId, d.* FROM watson_response_table watsonResponse CROSS JOIN LATERAL ( SELECT d2.* FROM ...

Modifying the $scope property on ng-click and redirecting with ui-sref

I am completely baffled by this situation. Here is the current status: https://i.sstatic.net/PJdb6.png Upon reaching this page, the following appears in the console: https://i.sstatic.net/aIJqd.png When I click on "lorem2", which has an ng-click funct ...

How can I prevent my service worker from caching text/html documents such as the index page?

When my PWA is offline, I want it to display the offline.html page. However, even when the homepage fails to fetch due to being offline, my service worker still uses cached text/html requests to retrieve the homepage. To create my PWA, I am utilizing work ...

How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

The outcome does not display default selected checkboxes

I am facing an issue with default checked items. The default checkbox is functioning properly, but when I click a button to display all checked items, the default checks are not being shown (they appear as unchecked). However, if I uncheck and then check t ...

Sequentially traverse the tree in reverse preorder fashion

My goal is to locate the element that is positioned directly above another element in the layout. This could mean the element is nested within several levels of the DOM structure, or it may involve moving up a few levels in the hierarchy. For instance: di ...