简体   繁体   中英

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);
            });
        }
    }
}]);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM