Combining two ng-model inputs in Angular for seamless data integration

New to Angular and seeking some guidance. I currently have two input fields, one for the area code and the other for the number.

// Input field for area code
<input area-input type="tel" required="true" name="area" 
ng-model="employee.home.area"></input>

// Input field for number
<input phone-input type="tel" required="true"
name="number" ng-model="employee.home.number"></input>

Is it possible to combine these fields into one, displaying the area code followed by the number?

Thank you in advance for any suggestions or assistance provided.

Answer №1

If you want to create a personalized directive, you can utilize the parsers and formatters functionalities available in ngModelControllers

By doing this, you'll end up with something similar to the following example:

angular.module('myApp', []).
controller('customCtrl', function($scope,$timeout) {
  $scope.info = {location : {city:'New City', zipCode:'12345'}};
  })
  .directive('postalCode', function() {
    function formatPostal(value) {
      console.log('format',value);
          if (!value) return;
          if (!value.zipCode) return value.city;
          value.city = value.city||'';
          return value.city + "-" + value.zipCode;
        }
    return {
      require: 'ngModel',
      scope:{
        ngModel:'='
      },
      link: function(scope, element, attrs, ngModel) {
        scope.$watch(function(){return scope.ngModel;},function(n){
          if(!n) scope.ngModel={city:"",zipCode:""}
          console.log('watch',n);
          ngModel.$viewValue= formatPostal(n);
          ngModel.$render();
        },true);
        
        ngModel.$formatters.push(formatPostal);
        ngModel.$parsers.push(function(value) {
          console.log(value, value.split('-'));
          var parts = value.split('-');
          return {
            city: parts[0],
            zipCode: parts[1]||''
          };
        });
      }
    };
  })
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e49798b199809d8bd594879690939b">[email protected]</a>" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<div ng-app="myApp" ng-controller="customCtrl">
  <h1>Hello App!</h1>
    // First input field for city<br/>
    <input city-input="" type="text" required="true" name="city" ng-model="info.location.city" /> 
    <br/>// Second input field for zip code<br/>
    <input postal-code-input="" type="text" required="true" name="zipcode" ng-model="info.location.zipCode" />
    <br/><br/>
    //custom field. format: city-zipcode<br/>
  <input data-postal-code type="text" required="true" ng-model="info.location" />
  {{info}}
</div>

Answer №2

To incorporate the employee's home area and number into your HTML, try using

{{employee.home.area}}+{{employee.home.number}}
.

For the controller, utilize `employee.home.area+employee.home.number`

Hopefully this information proves useful.

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

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

The error has not been handled properly and is being thrown at line 174 in the events.js file

I encountered an issue while trying to request data from an API, resulting in a crash on any Windows server. Can someone lend a hand with this problem? Here is a snippet of my code: app.get("/js/2806/api/products/getAllDrugs", (req, res) => { co ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Button cannot be activated upon selecting a row

The goal is to activate a button when a row is selected. However, the button remains disabled even after selecting a row. Below is a snippet of the code as well as a screenshot showing the issue [error_1]: onInit: function () { var oViewMode ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

Tips for preserving cropped images

Obtained the code for cropping images from this specific link: The code snippet provided in the crop.php file is as follows: <?php /** * Jcrop image cropping plugin for jQuery * Example cropping script * @copyright 2008-2009 Kelly Hallman * More ...

What is the functionality of $templateCache?

I have some questions about how $templateCache resources work. Will the html/template be stored on the server-side? Or will it be stored in the browser's memory? If so, what are the memory limits? ...

Having difficulty importing app.js into other modules within ExpressJS

Having trouble importing app.js into other modules in ExpressJs. It imports successfully, but I can't use the functions defined in the app.js file. The code snippet I am working with is as follows: I have this app.js var app = express(); var express ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

The relevance of this concept in the classroom setting and within the setTimeout function is integral to

Having recently started learning JS, I have gone through various answers on the context of "this" with classes and setTimeout(), but I am facing a specific issue. I am struggling to understand the thought process or mental model behind the following code ...

Skipping is a common issue encountered when utilizing Bootstrap's Affix feature

I'm trying to implement Bootstraps Affix feature in a sticky subnav. <div class="container" data-spy="affix" data-offset-top="417" id="subnav"> I've adjusted the offset to ensure there's no "skip" or "jump" when the subnav sticks. Ho ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

Using Angular as a template engine: A simple guide

My goal is to utilize Angular as a template engine and then pass the resulting HTML code to another library. In my template file named template.html: <div><h1><span data-ng-show="details.rs">{{details.rs}}</span></h1></di ...

In Javascript, async functions automatically halt all ongoing "threads" when a new function begins

I have a dilemma with multiple async functions that can be called by the user at any point in time. It is crucial for me to ensure that all previously executed functions (and any potential "threads" they may have initiated) are terminated when a new functi ...

Guide to creating a reminder feature in NestJS

In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app. Currently, I am working on checking which reminders have been reached for all users in order to trigger remin ...

Trimming whitespace from strings within HTML tag attributes can be achieved using various methods

I have been reviewing the .cshtml pages of a website with the aim of adding ID attributes to various divisions and elements for testing purposes. These pages utilize AngularJS, and many of the elements I need to add ID attributes to are part of a list tha ...

Steps for resolving "TypeError: Unable to read properties of undefined (reading 'useSystemColorMode')"Ready to overcome this particular error message?

While working on a project with ChakraUI and React JS, I encountered an error at the start that read, "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')". I have not made any changes to the global theme in Chakra, j ...

What steps should I take to set up search paths for node modules in Code Runner within Visual Studio Code?

Just recently, I embarked on a Javascript course and successfully configured my Visual Studio Code to run JavaScript. Check out the code snippet that I came up with: const prompt = require('prompt-sync')(); var fname = prompt("First name please : ...

How to perform a table filtration in AngularJS with a focus on specific table columns

While conducting a search within my table data, I need to implement a filter that only targets a specific field at times. For instance, imagine a table with columns for number, name, and content. When entering text into the search box, I want it to search ...