How to use ng-href with absolute url?

前端 未结 3 2082
孤独总比滥情好
孤独总比滥情好 2021-02-12 23:04

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

3条回答
  •  没有蜡笔的小新
    2021-02-12 23:37

    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:

    {{link.title}}
    

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

提交回复
热议问题