Retrieving user input in Angular and showcasing extracted keywords

I want to give users the flexibility to customize the format of an address according to their preference.
To achieve this, there will be a text input where users can enter both keywords and regular text.
The goal is to detect when a keyword is entered, extract it from an object, and display it accordingly.

Here is the object structure:

$scope.address = {
        "addressline1": "Street Name",
        "addressline2": "City and County",
        "addressline3": "12",
        "country": "United Kingdom",
        "postcode": "XE12 2CV"
    }

This is the HTML markup:

<input ng-model='value' placeholder="Enter Address Keywords" type="text" />

The directive should accept any input in the text field - however - when a key word is entered as the 'value', the script should retrieve that from the address object and display it.

I am facing challenges in implementing this functionality.

Below is the JavaScript code snippet:

(function() {
'use strict';
 angular.module('testApp', [])
.controller('testController', hotelController)

function hotelController($scope, $http) {
var vm = this;
$scope.address = {
  "addressline1": "Street Name",
  "addressline2": "City and County",
  "addressline3": "12",
  "country": "United Kingdom",
  "postcode": "XE12 2CV"
}
 var regexMobile = /addressline[0-9]*$/;
 var match = regexMobile.exec($scope.address);
 var result = '';
 var startPoint = 1;

 if (match !== null) {
  for (var i = startPoint; i < match.length; i++) {
    if (match[i] !== undefined) {
      result = result + match[i];
    }
  }
  $scope.value = result;
   }
  }
 })()

JSfiddle Link

Any assistance would be greatly appreciated.

Answer №1

It seems like you are trying to create a feature where a label is displayed based on the user input in a textbox.

For example:

If the user types "addressline1", it should display "Street Name".

If this is your goal, the following demo should help:

UPDATE:

In response to the request from the author, this updated version demonstrates how to separate items by comma and display the values corresponding to their keys:

(function() {
  angular
    .module('testApp', [])
    .controller('testController', hotelController);

  hotelController.$inject = ['$scope'];

  function hotelController($scope) {
    $scope.address = {
      "addressline1": "Street Name",
      "addressline2": "City and County",
      "addressline3": "12",
      "country": "United Kingdom",
      "postcode": "XE12 2CV"
    }

    $scope.change = function() {
      $scope.label = "";
      $scope.value.split(", ").forEach(function(value) {
        for (var addressKey in $scope.address) {
          if (addressKey == value) {
            $scope.label += " " + $scope.address[addressKey];
          }
        }
      })
    }
  }
})();
<!DOCTYPE html>
<html ng-app="testApp">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="testController">
  <section class='container'>
    <h5>Type in keyword</h5>
    <p>Custom directive which filters out keywords from an object and outputs them as text</p>
    <input type="text" ng-model="value" placeholder="address1, address2, address3, address4" ng-change="change()">
    <hr>
    <span ng-bind="label"></span>
  </section>
</body>

</html>

Answer №2

To achieve the desired outcome, follow the steps below:

HTML:

<main data-ng-app='testApp'>
  <section data-ng-controller='testController' class='container'>
    <h5>Enter a keyword</h6>
  <p>Custom directive that filters keywords from an object and displays them as text</p>

  <input ng-model='value' ng-keyup="test()" placeholder="address1, address2, address3, address4" type="text" />
 <div ng-repeat="x in keys| filter:value" ng-show="value">   
    {{x}} : {{address[x]}}
    </div>
</section>
</main>

JS:

(function() {
  'use strict';
  angular.module('testApp', [])
    .controller('testController', hotelController)

  function hotelController($scope, $http) {
    var vm = this;
    $scope.address = {
      "addressline1": "Street Name",
      "addressline2": "City and County",
      "addressline3": "12",
      "country": "United Kingdom",
      "postcode": "XE12 2CV"
    }

    $scope.keys = Object.keys($scope.address);

    $scope.test = function() {
      $scope.result = $scope.address[$scope.value];
    }
  }

})()

Codepen-http://codepen.io/nagasai/pen/vKjJQV

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

Setting the height to 100% on the body and html tags can lead to scrolling problems

After implementing the CSS code below, I have encountered some unexpected behavior: body, html{height:100%; overflow-x:hidden} Despite vertical scrollbars appearing as intended when the page exceeds screen height, detecting the scroll event on the body e ...

Ajax: Cross-Domain Request Blocked: The Same-Origin Policy prevents access to the external resource at

I am running an MVC Web API Service on two servers. When accessing it through C# using WebClient and HttpClient, as well as through Postman or directly pasting the service URL in the browser, everything works fine. However, when trying to consume it throug ...

Customize Your AJAX POST URL with Radio Buttons - A Step-by-Step Guide

I'm looking for some guidance on how to use AJAX to change the post URL based on a radio button selection. Do I need to use an if statement or is there another way? var barray = []; function cbutton() { $('input:radio[name="cheking"]:checke ...

Activation of Angular Watch upon newValue alteration

Is there a way to prevent triggering the watch multiple times when changing values based on other values in a repeat loop? Here is my current watch function: $scope.$watch('objlist', function(newValue, oldValue) { $scope.counter += 1; ...

Retrieving Outdated Information through the Express Framework

Whenever I make a fetch request to a node express server, it sometimes returns old data that was previously fetched from the same endpoint. This issue occurs sporadically but seems to happen more often than not. Even after disabling Cache-Control in the f ...

Decapitalizing URL string in jQuery GET request

Check out my code below: $.get('top secret url and stuff',function(data){ console.log($("[style='color:white']", data.results_html)[0].innerHTML); window.html = document.createElement('d ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...

Unfulfilled expectation of a promise within an array slipping through the cracks of a for loop

I have a function that generates a Promise. Afterward, I have another function that constructs an array of these promises for future utilization. It is important to note that I do not want to execute the promises within the array building function since so ...

Instructions for running a script from a personalized NPM package

I have developed a unique NPM package that includes a script I want to run from another project. Here is an overview of my package: myScript.js console.log("The script has been executed!"); package.json { "name": "@myscope/my-script", "version": "0. ...

What is the process of creating a color range in Java?

I am looking for a way to input a 6-digit RGB-hex number and then be able to click on a button that will display the corresponding color name. Unfortunately, I have not been able to find a color library in Java that can provide me with the names of arbitra ...

The method options.domAPI is not a valid function in this context

While attempting to customize global variables using stylus config in Vuetify, I discovered that it is no longer supported. To address this issue, I executed the following command to install the necessary loaders: npm i --save-dev stylus stylus-loader css ...

Html5Mode - solving the problem of page refreshing in angularjs

I've been developing an angularJS app that utilizes URLs in the following format during development: http://localhost:6001/#/home/index http://localhost:6001/#/content/index Since I plan for the app to be accessible on desktop browsers as well, I wa ...

Choose the specific selector following the current selector

Consider this example of code: <script> $(document).ready(function () { $('span').each(function () { $(this).html('<div></div>') ; if ( $(this).attr('id') == 'W0' ...

A guide on iterating through JSON output in AngularJS using PHP arrays

I am a beginner in AngularJs and currently working on creating a website with Angular.js and PHP. I am facing some challenges when it comes to displaying data from a JSON object. My controller $scope.careprovider = function() { $http.post(&apo ...

Learn how to personalize your Material UI icon by incorporating a plus symbol

Is it possible to add a plus sign to material ui icons? I currently have the following icon: import ApartmentIcon from '@mui/icons-material/Apartment'; https://i.sstatic.net/FejuX.png I would like to add a plus sign to this icon, similar to t ...

Numerous social media sharing buttons conveniently located on a single webpage

Currently, I am working on a research database project where the goal is to allow users to share articles from the site on various social networks such as Facebook, Twitter, LinkedIn, and Google+. To achieve this, I successfully implemented share buttons ...

The functionality of the AJAX Script is failing to load properly on mobile devices

Currently, I am undertaking a project that involves ESP32 Arduino programming to create a webpage where users can interact with buttons to activate relays. Additionally, I have implemented a slider using a short script. This project is inspired by the ESP3 ...

Retrieve the unique payment ID generated from the database and present it on the frontend

Greetings, I am currently working on integrating a payment processor and I require the automated generation of the corresponding payment ID in the backend. On the frontend side, I have implemented JS to request data from the backend, but I'm facing ...

The tip display script is unable to revert back to its original content

I managed to show a block of text in a td after a mouseover event, but I want to revert back to the original content on mouseout/mouseleave. The code I used is below. Please help. I am getting an undefined error when running the code. I suspect the issue l ...

Using ThreeJS to Load a Texture from an ArrayBuffer in JavaScript

If I have a JavaScript ArrayBuffer containing binary image data along with the image extension (such as jpg, png, etc), I want to create a ThreeJS Texture without the need for an HTTP request or file load as I already have the binary information. For exam ...