Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert generic text string in json object into valid url using Angular

This is my first Stack Overflow question so bear with me (I almost always find what I need or figure it out myself but this time is different since I'm just getting my feet wet with Angular).

I have a directive the grabs the name and url from a json object and builds the html with the name and an href. The problem is, the json response from the url object is a regular text string entered by a user from a CMS and and it's currently not being validated on the backend. Therefore, the URL can look like www.blah.xxx or http://blah.xxx and so on. Is there an Angular way without using a plugin where I can tell the output to check that the url has http:// and if it doesn't then add it? Or is there a good plugin that will do the trick easily?

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);
            });
        }
    }
}]);
like image 594
thinkbliss Avatar asked Apr 25 '26 15:04

thinkbliss


1 Answers

You can simply check every time if it's contains already the http in the beginning of the url:

 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>';
     }

But if you want a more sophisticated way, check this snippet

like image 158
Dhia Avatar answered Apr 28 '26 04:04

Dhia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!