How to use ng-href with absolute url?

Goran Obradovic picture Goran Obradovic · Feb 7, 2014 · Viewed 21.6k times · Source

I'm still new to angularjs, and I have a problem that I seem to not be able to find solution, and I don't have time to go look into angular source.

This is my scenario:

I have some json data with collection of urls that I want to show on screen. I have an element with ng-repeat="link in links" and inside I have

<a ng-href="{{link.url}}">{{link.title}}</a>

That works, but all links are pointing to mydomain/apppath/valueoflink.title I want them to be absolute, only valueoflink.title without any prefix.

How to tell angular that it is absolute not relative url?

Answer

Tonven picture Tonven · Dec 18, 2014

As Goran said, his solution will work only if all urls are like 'www.google.com'.

If you have a combination of different types of the urls, e.x. 'www.google.com', 'https://github.com', 'http://goo.gl', 'github.com', you can use ng-href with an angular filter:

<a ng-href="{{link.url|myFilter}}">{{link.title}}</a>

and a filter, which will append 'http://' to your url, if it starts with 'www':

'use strict';
myApp.filter("myFilter", function () {
    return function (link) {
        var result;
        var startingUrl = "http://";
        var httpsStartingUrl = "https://"; 
        if (link.startWith(startingUrl) || link.startWith(httpsStartingUrl)) {
            result = link;
        }
        else {
            result = startingUrl + link;
        }
        return result;
    }
});
String.prototype.startWith = function (str) {
    return this.indexOf(str) == 0;
};