Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular.

I have a directive that pulls the name and URL from a JSON object and generates HTML with the name and a hyperlink. The issue is that the JSON response for the URL can be entered in various formats by users using a CMS, without any backend validation. This means the URL can appear as www.blah.xxx or , among other possibilities. Is there an Angular solution (without relying on a plugin) to check if the URL includes "http://" and automatically add it if not? Or perhaps there's a reliable plugin that can handle this task effortlessly?

angular.module('pwrApp')
    .directive("getPrimaryCareProviderName", [function() {
        return {
            restrict: "A",
            link: function(scope, elem, attrs) {

            scope.$watch('primaryCareProvider', function() {
              var output = "";

                if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
                    output = scope.primaryCareProvider.name;
                }else{
                    output = '<a href="'+scope.primaryCareProvider.url+'" target="_BLANK">'+scope.primaryCareProvider.name+"</a>";
                }

                elem.html(output);
            });
        }
    }
}]);

Answer №1

To ensure that the URL starts with "http://" before displaying it as a link, you can add a simple check:

 if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
           output = scope.primaryCareProvider.name;
     }
     else{
           var url = scope.primaryCareProvider.url
           if (url.indexOf("http://") != 0){
              url = "http://" + url;
           }
           output = '<a href="'+url+'" target="_BLANK">'
                    +scope.primaryCareProvider.name+'</a>';
     }

If you're looking for a more advanced method, you can explore this sample code snippet

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 Django application is failing to interact with the AJAX autocomplete functionality

After typing the term "bi" into the search bar, I expected to see a username starting with those initials displayed in a dropdown list. However, nothing is showing up. Here are the codes I have used: search.html <html> <div class="ui-widget"> ...

Enhancing User Experience with AJAX and JSON in Servlet JSP Applications

I've been working on my school project for a while, but I'm having trouble with the login page. Every time I try to log in, I receive a PARSING ERROR message like this: Error Login AJAX For the login process, I am using a simple servlet that co ...

Using CSS and Vue, you can customize the appearance of inactive thumbnails by displaying them

My goal is for a clicked thumbnail to display in color while the others show as grey. The active thumbnail will be in color, and I want inactive thumbnails to appear in grey. Here is what I am trying to achieve: Vue.component('carousel', { ...

What causes the object to be updated with new values when I update reference variables in JavaScript?

Imagine having an object named x with values x = { a: 'abc', b: 'jkl' }, Next, I am assigning this object x to a new local variable y using var y = x. Now, when the value of var y changes as y.a = 'pqr', y.b = 'xyz&apos ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...

Navigating through the drupal module directory using JavaScript

Is there a way to retrieve the module path in Drupal 7 from which a .js file was loaded? Although JS is primarily a front-end language, is it possible that Drupal includes this information within the Drupal object? Essentially, I am trying to achieve so ...

Updating an element within a JSON object in PHP: A step-by-step guide

I have a JSON object that looks like this: { "fields" : [ { "name" : "news_title", "type" : "text", "value" : "old title" }, { "name" : "news_co ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

Creating a PDF document with multiple pages using a PHP loop, integrating with AJAX, and utilizing the m

Looking for assistance with a plugin development project involving PDF generation using AJAX. The challenge lies in generating multiple PDFs for each user within a loop. The goal is to create PDFs with multiple pages for individual users. If that's n ...

Assigning an object as a value in JSON-LD expansion

Recently, I attempted to convert `JSON` data into `JSON-LD` format and had a thought about utilizing the `JSON-LD` expansion algorithm to build my own converter. By defining my schema as a context and running the expansion algorithm, I hoped to smoothly ca ...

What is the best way to send a message to multiple clients using different workers in both WebSocket and Express?

Currently in my express app, I am utilizing clusters and the ws package to run my project with a socket connection. The issue arises when a client connects to the socket - only one worker (such as worker with id 1) handles the connection. If another client ...

Show the outcome of a function inside an ng-repeat loop

I have encountered a roadblock in my Angular project. I am populating a table with run data retrieved from a REST call using ng-repeat. Each run includes GPS coordinates, and I have a function that converts these coordinates into the corresponding city nam ...

Is it possible to display the entire page upon destroying the controller in Angular?

Is there a way to detect in $destroy if it's possible to load the full page when transitioning from one controller to another? ...

Issue: The 'in' operator is not allowed for searching

Passing Data from Child Component to Parent Component in AngularJS In my AngularJS project, I have two components: search and form. The search component is a child of the form component. Within the search component, there is a text input field that contai ...

Watching a live video stream in real-time using WebRTC with React

Here is the HTML code <video ref={videos} autoPlay ></video> <Button onClick={() => navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((mediaStream) => { videos.srcObject = mediaStream; videos.onloadedmetad ...

Utilize AngularJS ngResource to transmit JSON data to the server and receive a response

My Angular JS application requires sending data to the server: "profile":"OLTP", "security":"rsh", "availability":"4", "performance": { "TRANSACTION_PER_SEC":1000, "RESPONSE_TIME":200, "CONCURRENT_CONNECTION_COUNT":500, "STORAGE_SIZE": ...

Choose2 cluster group on JSON/Ajax organizing request

I have been attempting to use Select2 with JSON/Ajax call to create a group, following this structure: <optgroup label="Property Reference"> <option value="1">5742</option> <option value="2">5788</option> < ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...