Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component.

Here are a couple of examples:

format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)'

or

format="'(tz, offset) location'" === '(EDT -04:00) New York'

The goal is to display the value in the specified format with parentheses included. One possible approach is creating an array with the required format? Given the following string, how can I generate the corresponding array:

'(utc, offset) location (tz)' === ['(', 'utc-code', 'offset-hours', ')', 'location', '(', 'tz-code', ')'];

'(tz, offset) location' === ['(', 'tz', 'offset', ')', 'location']

Answer №1

To pass the value, you can utilize component binding. The function $doCheck will be triggered in each digest cycle to identify and respond to changes in the bindings.

I've implemented a straightforward logic using regular expressions to showcase the data with a specified input format. This method might prove more effective compared to your array-based approach.

angular.module('app',[])
.controller('appCtrl', function($scope){
  $scope.format = '(offset) location (tz)';
})
.component('myComponent', {
  template: '<div>{{$ctrl.formattedValue}}</div>',
  controller: myComponentCtrl,
  bindings: {
    format: '='
  }
});

function myComponentCtrl(/*your DI goes here*/){
  console.log('log from component: format->'+this.format);
  var self = this;
  this.formattedValue = '';
  
  this.$doCheck = function(){ 
    var sampleDateObject = {
      tz: 'CDT',
      offset: '-4:00',
      location: 'Chicago',
      year: 2017
    }
    self.formattedValue = self.format.replace(/([a-z]+)/gi, function(match){
      return sampleDateObject[match]?sampleDateObject[match]:match;
    });
  };
}

myComponentCtrl.$inject = [/*your DI goes here as string*/];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<div ng-app="app" ng-controller="appCtrl">
  <my-component format="format"></my-component>
  <my-component format="'(tz, offset) location, year'"></my-component>
</div>

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

AngularJS showcasing data in a visually appealing layout

Successfully connected API and displaying data, but now encountering an issue with formatting the data into a table. When using ng-repeat="item in items", if used within a tr tag, only one row is shown. If used within a tbody tag, it repeats the tbody. He ...

When employing ng-repeat, the ui-bootstrap tooltip fails to function as expected

I'm trying to implement tooltips for a series of buttons using the ui-bootstrap tooltip directive within an ng-repeat loop, as shown below: <button ng-repeat="label in labels" tooltip="{{label}}">{{label}}</button> However, I've enc ...

No alteration is made to the value stored in the variable $scope.data

I am facing an issue with the values in $scope.data that are not changing. You can view the problem on this jsfiddle - jsfiddle When you first set Currency: 'UAH' and then change it to Currency: 'RUB', the value of Qty:2 appears to be ...

Toggle the visibility of multiple divs depending on a specific attribute value

I previously inquired about this issue, but I believe my wording was unclear and the responses focused on how to display or hide a group of divs when clicking a button. While I understand that concept, my specific challenge is slightly different. Let me pr ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Changing the row property value of a textarea dynamically based on text input in ReactJS

Here is what I have tried: <textarea rows='2' onChange={e => setSomething(e.target.value)} className='form-control text-area ' value={something} placeholder='write something'> </textarea> output: Expected ...

A guide to implementing the map function on Objects in Stencil

Passing data to a stencil component in index.html <app-root data="{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f5d2d8d4dcd99bd6dad8">[email protected]</a>, <a href="/cdn-cgi/l/email-pro ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

Is there a way to extract JSON keys that begin with a numerical value?

I am attempting to retrieve JSON data from sparkfun using ajax: var token = "someToken"; var jsonData = $.ajax({ url: "https://data.sparkfun.com/output/" + token + ".json", data: { page: 1 }, dataType: "jsonp", }).done(function (results) { ...

What's the reason "console.log()" doesn't function on this particular site?

When I go to https://www.google.com/ and enter console.log("Hello world!") into the Chrome DevTools console, it prints "Hello world!" as expected. However, when I try the same command on , nothing shows up in the console. Why doesn't it work for this ...

Error 404: Jquery Fancy Box Not Found

Help needed with JQuery FancyBox: I encountered a 404 error when trying to enlarge small images. Here is the code that I used: <a class="fancybox-buttons" data-fancybox-group="button" href="images/gallery/1_b.png" style="margin-right:100px;"><im ...

Updating HTML content using jQuery by iterating through an array

When I write the following HTML code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <h1 id="message"> </h1> and include the corresponding JavaScript code: messages = ["Here", "are", ...

Utilizing Ajax for Efficiently Updating a Singular Field within a Designated Object

How can I use Ajax to Update a Single Field in a Specific Object? I have a table in my postgres database with numerous records. I am interested in using a jquery Ajax request to update just one field in a particular object within that table. Is it possibl ...