Tips for effectively utilizing tags in AngularJS search functionality

I attempted to implement a search box that utilizes tags, shown in the image below. Despite trying to use bootstrap tags, it did not work as intended.

Here is a visual representation of how the search should be displayed:

https://i.sstatic.net/COqai.png

Answer №1

Take a look at this fiddle:

https://jsfiddle.net/elmacko/hu2yngat/55/

You have the flexibility to customize the filter based on your requirements. Further refinement is possible, but this will give you a starting point.

angular.module("app", [])
.directive("badgeSearch", function()
{
    return {
    restrict: "E",
    replace: true,
    template: `
        <div class='badge-search-container'>
          <a href='#' ng-click='removeBadge($index)'
             class='badge badge-primary search-badge'
             ng-repeat='badge in badges track by $index'>{{ badge }}
          </a>
          <form class='badge-search-form'>
             <input class='badge-search-input' type='text'
                    ng-model='search'>
             <button class='btn btn-primary' type='submit'
                     ng-click='addBadge()'>
               Add
             </button>
           </form>
         </div>`,
    controller: "badgeSearchController",
    scope: {},
    link: function(scope, element, attributes)
    {
        scope.badges = [];
      scope.search = "";

      if(attributes.ngModel)
      {
        scope.modelController = element.controller("ngModel");

        scope.modelController.$isEmpty = function(value)
        {
          return !value || value.length === 0;
        };

        scope.modelController.$render = function()
        {
          scope.badges = scope.modelController.$viewValue;
        };
      }
    }
  };
})
.controller("badgeSearchController", function($scope)
{
  $scope.addBadge = function()
  {
    if($scope.search)
    {
        $scope.badges.push($scope.search);
        $scope.search = "";
    }
  };

  $scope.removeBadge = function(index)
  {
    $scope.badges.splice(index, 1);

    // This will trigger ng-change to fire, even in cases where $setViewValue() would not.
    angular.forEach($scope.modelController.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        this.$exceptionHandler(e);
      }
    });
  };
})
.filter("badgeFilter", function()
{
    return function(items, badges)
  {
    if(!badges || !badges.length)
    {
        return items;
    }

    return items.filter(function(item)
    {
        return badges.indexOf(item) != -1;
    });
  };
})
.controller("mainController", function($scope)
{
    $scope.items = [
    "first",
    "second"
  ];
  $scope.badges = [];
});

html

<div ng-app="app" ng-controller="mainController">
  <badge-search ng-model="badges"></badge-search>

  <ul class="list-group">
    <li ng-repeat="item in items | badgeFilter:badges" class="list-group-item">{{ item }}</li>
  </ul>
</div>

css

.badge-search-input
{
  height: 100%;
  border: 0px;
  outline: none;
}

.badge-search-form
{
  display: inline-block;
}

.badge-search-container
{
  padding-left: 8px;
  height: 39px;
  margin: 16px;
  border: 1px solid black;
  border-radius: 0px 4px 4px 0px;
}

.search-badge
{
  margin-right: 8px;
}

Answer №2

Implement the ngTagsInput directive:

<html>
<head>
    <script src="angular.min.js"></script>
    <script src="ng-tags-input.min.js"></script>
    <link rel="stylesheet" type="text/css" href="ng-tags-input.min.css">
    <script>
        angular.module('myApp', ['ngTagsInput'])
            .controller('MyCtrl', function($scope, $http) {
                $scope.tags = [
                    { text: 'just' },
                    { text: 'some' },
                    { text: 'cool' },
                    { text: 'tags' }
                ];
                $scope.loadTags = function(query) {
                     return $http.get('/tags?query=' + query);
                };
            });
    </script>
</head>
<body ng-app="myApp" ng-controller="MyCtrl">
    <tags-input ng-model="tags">
        <auto-complete source="loadTags($query)"></auto-complete>
    </tags-input>
</body>
</html>

source

https://github.com/mbenford/ngTagsInput

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

The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here Below is my controller: class ReadCtrl constructor: (@$sco ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Implementing angularjs into grails version 2.3.4

I have a page named index.gsp and I want to include my angularjs library files: <head> <meta name="layout" content="main" /> <title>Title Page</title> <!-- loading angularjs --> <r:require module="angular" /> </hea ...

In Javascript, objects within local scope cannot be accessed from nested functions

I'm currently working on a function that is meant to retrieve an object from a PHP file located on a different page. I've implemented the jQuery ajax function to handle the JSON retrieval, and it seems to be functioning as intended. However, I&ap ...

Is there a way to generate a fresh array by filtering an array of objects based on a single value?

I am currently working with an array of objects: const dummyLinkRows = [ { id: 'entity:link/1:en', categories: [ { name: 'Human Resources' }, { name: 'Social' } ], nam ...

Issue with Datepicker not updating when triggered by event handler

Having an issue with my material-UI datepicker where the date is not updating correctly when I try to select a new one. The initial value set in useState works fine, but I want the datepicker to smoothly update when I choose a different date. You can see a ...

Utilizing Regular Expressions in JavaScript to extract packages from an Android manifest document

When it comes to Android APK files, the manifest files play a crucial role: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" android:versionCode="1" ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...

Is there a way to attach a React component to an HTML element called i?

I've been implementing the winbox modal library and have encountered an issue when trying to add a React node to it. The modal offers an html parameter that accepts an HTML string like div.innerHTML = <div>hello</div>. The code snippet is ...

Encountering a malfunction while executing an npm command specified in the package.json file

Currently, I am following a tutorial on Node, React, and Express on Udemy. In the tutorial, when I execute the command npm run data:import I encounter the following error: undefined npm ERR! code ELIFECYCLE npm ERR! errno 1 ...

Create distinct 4-digit codes using a random and innovative method, without resorting to brute force techniques

I am working on developing an application that requires generating random and unique 4-digit codes. The range of possible codes is from 0000 to 9999, but each day the list is cleared, and I only need a few hundred new codes per day. This means it's fe ...

What is the best way to integrate my PHP regular expression into Node.js code?

I recently encountered an issue when trying to convert a regular expression from PHP to Node.js. The output I'm receiving in Node.js is different from what I expect, and I suspect it has to do with my implementation of PREG_SET_ORDER in Node.js. Here ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

Using React to organize and showcase text messages in categorized sections

I am looking to organize text messages into different sections based on when they were received: This includes messages received today, yesterday, this week, this month, and continuing in month intervals as needed... For example: https://i.sstatic.net/R ...

Stop React Form from automatically submitting by preventing automatic submission

I am currently facing an issue with a form that includes a rich text editor and a submit button. The problem arises when the style buttons in the rich text editor are clicked, causing the form inputs to submit unintentionally. My goal is to prevent this b ...

Problem with AngularJS function execution - require a delay in executing the second function

I am developing a small utility in AngularJS to manage the shopping cart for users. Here is the code snippet from my cart-service.js file: var myStoreCartService = angular.module("myStoreCartService", []); myStoreCartService.factory('Cart', fu ...