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

Use yarn to install both devDependencies and dependencies simultaneously

Can yarn be used to install devDependencies and dependencies simultaneously? For instance, if I need to install react as a dependency and webpack as a dev dependency. Typically, I would have to execute two separate commands like shown below: yarn add reac ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

Using an image as an onclick trigger for a JavaScript function

I am working on a registration page as part of my university project where users can create an account and store their information in a MySQL database. One feature I'm implementing is the ability for users to select an avatar picture. Below is the co ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

open a fresh modal by closing the existing modal using just one button

I am trying to implement a unique functionality in my bootstrap based project. I have one modal that I want to link to another modal, however, I am facing some challenges in achieving this. Currently, I am attempting to use the modal.close() and .modal(&ap ...

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

Narrow down your search results with date range filtering in Angular Material

Seeking guidance as a newcomer to Angular Material, I am trying to implement a date range filter for a table of N results. The options in the filter select are (1 day, 5 days, 1 week, 15 days), which are populated using a variable JS vm.rangos=[ {id ...

Two interdependent select fields

I am currently working on creating two select fields where, upon selecting an option in the first field, some options in the second field should be hidden. I have almost achieved this, but my script is unable to locate certain options in the first select f ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Troubleshooting: Issue with Bootstrap 4 navbar toggle button functionality

Is it possible to manually control the opening and hiding of the navbar when the toggle button is clicked in bootstrap 4? Currently, my navbar automatically opens and closes when clicking the toggle button. Any suggestions on how to modify this behavior wo ...

Have the getter functions for reactive objects in Vue 3 been transformed into computed values?

Is the memoization of bookCount in this instance handled equivalently to a computed reference? const author = reactive({ name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - ...

What steps should I take to set up Sublime to consistently open in the same directory?

I need Sublime to always open a specific folder... my_folder Is there a way to configure Sublime so that it always opens this folder when I click on the icon? When I manually quit Sublime using the menu, it remembers my last folder upon reopening. Howe ...

transforming a dictionary string into a JSON string

Is there a way to transform my dictionary into a JSON string and then back again in C#? I have a Dictionary<string,string> that I need to convert to a JSON string, and then reverse the process to get back my original Dictionary. How can this be ac ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

What is the best way to dynamically convert a lodash object (specifically a filter object) into jQuery's listview component?

After referencing the answer to this topic as my first step, which can be found here, my next goal is to utilize a filter function to retrieve all matching entries from a JSON file based on a search term. The objective is to loop through each match and con ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

"Real-time communication: Using SignalR to send personalized messages to the logged in

I have a web app project and an Angular 2 project. I want to use SignalR to send messages from the server. I came across this article that explains how to implement it. However, I am unsure of how to send a message to the current user. This is the C# code ...

Retrieving JSON data without using Jquery's Ajax function

I was wondering if there is any way to retrieve the results of a jQuery AJAX call and store them in a traditional variable for use as a function. Here's an example: function getPoints(){ //An array of JSON objects var Points; ...