Reputation: 1241
I've made a simple app similiar to hacker news to understand how works with angularJS.
I have a problem, when I submit link input like:
I type "http://www.foo.com" is submitted and it returns as "www.foo.com"
otherwise, I type "www.foo.com" is submitted and it returns as "localhost:3000/www.foo.com"
I couldn't figure out how to get rid of current location of this url after of submitting a link without HTTP://
There no special conditions to manipulate this link, my app is using a lib for angularjs:
angular-ui-router.js
There is code
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Link test</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
<script src="js.js"></script>
</head>
<body ng-app="scopeExample">
<div ng-controller="MyController">
Your link:
<input type="text" ng-model="url">
<button ng-click='sayLink()'>post link</button>
<hr>
<a ng-href="{{link}}" target="_self">{{link}}</a>
</div>
</body>
</html>
JS:
(function(angular) {
'use strict';
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.url = 'www.zombo.com';
$scope.sayLink = function() {
$scope.link = $scope.url;
};
}]);
})(window.angular);
There an live preview http://plnkr.co/edit/iDT0C4vi22mGMuxw8z9s?p=preview
Can anyone explain why is this?
Thanks!
Upvotes: 0
Views: 2205
Reputation: 27012
It's not really anything to do with Angular: it's just setting the href
attribute on the link to exactly what was typed in the input (minus any leading/trailing white space I think).
It's due to how browsers handle relative/absolute links in such tags:
If the link starts with a protocol, like http://
, then it treates is as a full URL
Otherwise, if the link starts with a forward slash /
it treats the link as being an absolute path on the current domain/protocol
Otherwise, it treats the link as relative to the current base href (which can be the current page, or can be the same as the root path on the domain depending on what the <base>
tag specifies)
This is what I think is happening with www.foo.com
. Your base href must be http://localhost:3000/
, and so the browser treats the link as http://localhost:3000/www.foo.com
To sort this, you can just add the protocol if it's missing. Taking from https://stackoverflow.com/a/3543261/1319998 , you could do something like:
$scope.sayLink = function() {
if (!/^https?:\/\//i.test($scope.url)) {
$scope.link = 'http://' + url;
}
};
Upvotes: 4