Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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);
            });
        }
    }
}]);
share|improve this question
    
Check this regex out. You can test for this regex, and add "http://" if you need to. IMO there's no need to import a plugin (and the overhead) for this. – UtsavShah yesterday
    
$compile(output); Have a look at the docs: docs.angularjs.org/api/ng/service/$compile – Leo Farmer yesterday
    
I think you would be relatively safe just checking for the existence of :// in the url using indexOf(). – Matt Way 23 hours ago

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.