[英]Convert generic text string in json object into valid url using Angular
This is my first Stack Overflow question so bear with me (I almost always find what I need or figure it out myself but this time is different since I'm just getting my feet wet with Angular). 这是我的第一个Stack Overflow问题,所以请耐心等待(我几乎总能找到我需要的东西或者自己弄清楚,但这次是不同的,因为我刚刚用Angular弄湿了)。
I have a directive the grabs the name and url from a json object and builds the html with the name and an href. 我有一个指令,从json对象中获取名称和url,并使用名称和href构建html。 The problem is, the json response from the url object is a regular text string entered by a user from a CMS and and it's currently not being validated on the backend.
问题是,来自url对象的json响应是用户从CMS输入的常规文本字符串,并且它当前未在后端验证。 Therefore, the URL can look like www.blah.xxx or http://blah.xxx and so on.
因此,URL可以看起来像www.blah.xxx或http://blah.xxx等。 Is there an Angular way without using a plugin where I can tell the output to check that the url has http:// and if it doesn't then add it?
有没有使用插件的Angular方法,我可以告诉输出检查url是否有http://如果没有,那么添加它? Or is there a good plugin that will do the trick easily?
或者是否有一个很好的插件可以很容易地做到这一点?
angular.module('pwrApp')
.directive("getPrimaryCareProviderName", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
scope.$watch('primaryCareProvider', function() {
var output = "";
if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
output = scope.primaryCareProvider.name;
}else{
output = '<a href="'+scope.primaryCareProvider.url+'" target="_BLANK">'+scope.primaryCareProvider.name+"</a>";
}
elem.html(output);
});
}
}
}]);
You can simply check every time if it's contains already the http in the beginning of the url: 你可以每次检查它是否已包含url开头的http:
if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
output = scope.primaryCareProvider.name;
}
else{
var url = scope.primaryCareProvider.url
if (url.indexOf("http://") != 0){
url = "http://" + url;
}
output = '<a href="'+url+'" target="_BLANK">'
+scope.primaryCareProvider.name+'</a>';
}
But if you want a more sophisticated way, check this snippet 但如果您想要更复杂的方法,请查看此代码段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.