我制作了一个类似于黑客新闻的简单应用程序,以了解如何使用angularJS。
我在提交链接输入时遇到问题,例如:
我输入“ http://www.foo.com ”已提交,并返回为“ www.foo.com”
否则,我将提交“ www.foo.com”,并返回“ localhost:3000 / www.foo.com”
在提交不带HTTP://的链接后,我不知道如何摆脱该URL的当前位置
没有特殊条件可以操作此链接,我的应用程序使用的是libjs用于angularjs:
angular-ui-router.js
有代码
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);
有实时预览http://plnkr.co/edit/iDT0C4vi22mGMuxw8z9s?p=preview
谁能解释为什么?
谢谢!
它与Angular并没有任何关系:只是将href
链接上的属性设置为与输入内容完全相同(减去我认为的任何前导/后缀空格)。
这是由于浏览器如何处理此类标记中的相对/绝对链接:
如果链接以协议开头(如)http://
,则将其视为完整网址
否则,如果链接以正斜杠开头,则将/
其视为当前域/协议上的绝对路径
否则,它将链接视为相对于当前基本href的链接(可以是当前页面,也可以与域上的根路径相同,具体取决于<base>
标记所指定的内容)
我认为这是正在发生的事情www.foo.com
。您的基本href必须为http://localhost:3000/
,因此浏览器会将链接视为http://localhost:3000/www.foo.com
要对此进行排序,如果缺少协议,则只需添加协议即可。从https://stackoverflow.com/a/3543261/1319998获取,您可以执行以下操作:
$scope.sayLink = function() {
if (!/^https?:\/\//i.test($scope.url)) {
$scope.link = 'http://' + url;
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句