[英]How to check if “http://” is included in url input in Angular.js app?
我是Angular.js的新手,正在嘗試構建一個簡單的新聞應用程序,在其中發布一些文本,並將該文本鏈接到url。
這是我的HTML:
<html>
<head>
<title>Angular News App</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="app2.js"></script>
</head>
<body ng-app="News" ng-controller="MainCtrl">
<div ng-repeat="post in posts">
<a href="{{post.link}}">
{{post.title}}
</a>
</div>
<form ng-submit="addPost()">
<input type="text" placeholder="Title" ng-model="title"></input>
<br>
<input type="text" placeholder="Link" ng-model="link"></input>
<br>
<button type="submit">Post</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
這是我的app2.js:
angular.module('News', [])
.controller('MainCtrl', [
'$scope',
function($scope){
$scope.posts = [
{title: 'Hotmail.com', link: 'http://www.hotmail.com'},
{title: 'Facebook.com', link: 'http://facebook.com'}
];
$scope.addPost = function(){
if(!$scope.title || $scope.title === ''){ return;}
if(!$scope.link || $scope.link === ''){ return;}
// if statement to be added here?
$scope.posts.push({
title: $scope.title,
link: $scope.link
});
$scope.title= '';
$scope.link= '';
};
}] );
所有這一切。
現在,我想檢查所提供的鏈接是否以“ http://”開頭,如果沒有,則將該鏈接連接到$ scope.link的開頭。 誰能告訴我該怎么做?
我覺得應該可以使用類似的東西:
if(!$scope.link.startsWith("http://)){
$scope.link = "http://" + $scope.link;}
並將其插入到app2.js中的其他if語句之后。
在此先感謝您,不勝感激!
湯姆
您可以使用此:
if(!$scope.posts.link.indexOf("http://")){
//Logic when url starts with HTTP protocol
}
此檢查您提供的鏈接的開頭是否有字符串“ http://”。
您可以這樣使用$ location:
var absolute_url = $location.absUrl();
var first_part = absolute_url.substring(0, 7);
if(first_part === 'http://'){
# do something here
}
不要忘記將$ location注入控制器
花了所有時間寫完問題之后。 我剛剛設法找出答案!:
if($scope.link.substring(0, 7) != "http://"){
$scope.link = "http://" + $scope.link;}
我以為我會離開這里,以防其他人想做類似的事情。
那https呢?
var url = 'https://www.google.es';
//var url = 'http://www.google.es';
//var url = 'www.google.es';
if(!url.match(/^https?:\/\//))
{
url = 'http://'+url;
}
console.log(url);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.