How to use angular variable in <a> tag - html

In my component I subscribe some basic data:
ngOnInit() {
this.data.getBasics().subscribe(
data => {
this.basics = data
}
)
}
I use them in html like this:
<h1>{{ basics.surname }}</h1>
and it works perfectly fine. A few of basics are the links. Assume basics.mypage to be "http://mypage.com". I would like to use it as a href in my html document. Something like this:
<a href={{ basics.mypage }}>Go to my page</a>
but that way it sends me to
http://localhost:4200/%7Bbasics.mypage%7D
How to use this variable inside tag?

Just insert {{basics.mypage}} into quotes
Go to my page

Use ng-href:
<a ng-href={{ basics.mypage }}>Go to my page</a>
or check that the data is properly formatted.

Another way is also available thats called property binding.
<a [href]="variableName"></a>
or
<a [attr.href]="variableName"></a>

Always prepend your absolute external links with protocol or // shortcut for http:// OR https:// depending on your app's protocol.
<div class="inline-icon-text">
<small class="text-muted d-md-none mr-3">Link</small>
<a [attr.href]="'//' + candidate.url" target="_blank" [title]="candidate.url">
<i class="material-icons">open_in_new</i>
</a>
</div>
Browsers treat URLs as a relative by default to facilitate in-app navigation.
As a side note, this behavior is not Angular-specific; other frameworks and plain sites behave exactly the same.
This also a great way of doing that.

Use this instead.
<a ng-href={{basics.mypage}}>Go to my page</a>
This is what I can gather from the Angular API here: Angular ngHref

Related

AngularJS - Modal view not showing [duplicate]

When both, href and ng-click attributes are defined:
Sign out
the href attribute takes precedence over ng-click.
I am looking for a way to raise priority of ng-click.
href is required for Twitter Bootstrap, I can't remove it.
This example from the angular documentation site just does href without even assigning it to an empty string:
[<a href ng-click="colors.splice($index, 1)">X</a>]
http://docs.angularjs.org/api/ng.directive:select
You can simply prevent the default behavior of the click event directly in your template.
<a href="#" ng-click="$event.preventDefault();logout()" />
Per the angular documentation,
Directives like ngClick and ngFocus expose a $event object within the scope of that expression.
Here is another solution :
Sign out
i.e. Just remove the # from the href attribute
You should probably just use a button tag if you don't need a uri.
Just one more hint. If you need real URL (to support browser accessibility) you can do the following:
template:
<a ng-href="{{link}}" ng-click="$event.preventDefault(); linkClicked(link)">{{link}}</a>
directive:
$scope.linkClicked = function(link){
// your code here
$location.path(link);
};
In this way your code in linkClicked() will have chance to execute before navigating to the link
In Angular, <a>s are directives. As such, if you have an empty href or no href, Angular will call event.preventDefault.
From the source:
element.on('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
Here's a plnkr demonstrating the missing href scenario.
This worked for me in IE 9 and AngularJS v1.0.7:
Logout
Thanks to duckeggs' comment for the working solution!
There are so many answers for this question here but it seems there is a bit of confusion about what's actually going on here.
Firstly, your premise
"href overrides ng-click in Angular.js"
is wrong. What is actually happening is that after your click, the click event is first handled by angular(defined by ng-click directive in angular 1.x and click in angular 2.x+) and then it continues to propagate(which eventually triggers the browser to navigate to the url defined with href attribute).(See this for more about event propagation in javascript)
If you want to avoid this, then you should cancel the event propagation using the The Event interface's preventDefault() method:
<a href="#" ng-click="$event.preventDefault();logout()" />
(This is pure javascript functionality and nothing to do with angular)
Now, this will already solve your problem but this is not the optimal solution. Angular, rightfully, promotes the MVC pattern. With this solution, your html template is mixed with the javascript logic. You should try to avoid this as much as possible and put your logic into your angular controller. So a better way would be
<a href="#" ng-click="logout($event)" />
And in your logout() method:
logout($event) {
$event.preventDefault();
...
}
Now the click event will not reach the browser, so it will not try to load the link pointed by href. (However note that if the user right clicks on the link and directly opens the link, then there won't be a click event at all. Instead it will directly load the url pointed by the href attribute.)
Regarding the comments about visited link color in the browsers. Again this has nothing to do with angular, if your href="..." points to a visited url by your browser by default the link color will be different. This is controlled by CSS :visited Selector, you can modify your css to override this behaviour:
a {
color:pink;
}
PS1:
Some answers suggest to use:
<a href .../>
href is an angular directive. When your template is processed by angular this will be converted to
<a href="" .../>
Those two ways are essentially the same.
Just write ng-click before href ..It worked for me
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script>
angular.module("module",[])
.controller("controller",function($scope){
$scope.func =function(){
console.log("d");
}
})</script>
</head>
<body ng-app="module" ng-controller="controller">
<h1>Hello ..</h1>
<a ng-click="func()" href="someplace.html">Take me there</a>
</body>
</html>
I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10
Logout
You can also try this:
<div ng-init="myVar = 'www.thesoftdesign'">
<h1>Tutorials</h1>
<p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>
I'll add for you an example that work for me and you can change it as you want.
I add the bellow code inside my controller.
$scope.showNumberFct = function(){
alert("Work!!!!");
}
and for my view page I add the bellow code.
<a href="" ng-model="showNumber" ng-click="showNumberFct()" ng-init="showNumber = false" >Click Me!!!</a>
Did you try redirecting inside the logout function itself? For example, say your logout function is as follows
$scope.logout = function()
{
$scope.userSession = undefined;
window.location = "http://www.yoursite.com/#"
}
Then you can just have
<a ng-click="logout()">Sign out</a>
Please check this
Logout
$scope.logout = function(event)
{
event.preventDefault();
alert("working..");
}
//for dynamic elements - if you want it in ng-repeat do below code
angular.forEach($scope.data, function(value, key) {
//add new value to object
value.new_url = "your url";
});
<div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>
This works for me
<a href (click)="logout()">
<i class="icon-power-off"></i>
Logout
</a>
<a href="#">
<span ng-click="logout()"> Sign out </span>
</a>
I did like this and it worked for me.

regex adding target="_blank" to all links but exclude ones that already have target="_blank" or links that have <a name="..."> and <a href="#...">

So I have this regex that I designed, but can't seem to exclude links on a page that already have target="_blank" or links that contain <a name="..."> or <a hre="#..."> How would I exclude links with target="_blank" and not add target="_blank" to anchor links?
Find: <a href=(".*)|([^#][^"]*)\\s>(\w.*)(</a>)
Replace: <a href=$1 target="_blank"$2$3
Regex is notoriously the wrong tool for this job.
HTML is structured data that regex doesn't understand, which means you run into exactly the sort of issues you're having: for any non-trivial problem, the many allowed variations in HTML structure make it very difficult to parse using string manipulation techniques.
DOM methods are designed for manipulating that sort of data, so use them instead. The following will loop through every <a> tag in the document, exclude those with no href attribute, those whose href begins with '#', or those with a name attribute, and set the 'target' attribute on the rest.
Array.from(document.getElementsByTagName('a')).forEach(function(a) {
if (
a.getAttribute("href") &&
a.getAttribute("href").indexOf('#') !==0 &&
a.getAttribute("name") === null
) {
a.setAttribute('target', '_blank'); // on links that already have this attribute this will do nothing
}
});
// Just to confirm:
console.log(document.getElementById('container').innerHTML)
<div id="container">
test
test2
test3
<a name="foo">test4</a>
</div>

Construct an html anchor for a Thymeleaf variable holding an abolute url (external to the app)

I have a variable in my Thymeleaf context, called r. r has a getUrl that returns an URL, something like www.a.co I want to create an HTML anchor http://www.a.co Is there any better way of doing it in Thymeleaf ? My solution is the following, but I don't really like it.
<a th:href="#{http://{path}(path=${r.url})}">
<span th:text="${r.url}"/>
</a>
There are a lot of different ways of doing this (depending on your needs). I guess I would prefer:
<a th:href="|http://${r.url}|" th:text="${r.url}" />
You might also be interested in one of these:
<a th:href="${'http://' + r.url}" th:text="${r.url}" />
<a th:href="'http://' + ${r.url}" th:text="${r.url}" />
<a th:href="#{${'http://' + r.url}}" th:text="${r.url}" />

Go to external url?

Okay, this is so simple yet I don't know how to do it.
I use vhost that makes localhost/wamp/www/blog/public become blog.dev
sample:
Stack Overflow
expected result: go to stackoverflow.com
what it actually does: go to blog.dev/stackoverflow.com
So, how should I do?
First of all, if you use a relative URL like above, your browser will assime that it's a URL relative to the URL you're currently browsing. That's why
<a href="stackoverflow.com">
links to blog.dev/stackoverflow.com
Replace
<a href="stackoverflow.com">
with the absolute URL
<a href="http://stackoverflow.com">
to get what you need.
Secondly, you could add target attribute to your URL if you want to open the link in a new window/tab:
<a href="http://stackoverflow.com" target="_blank">

Html links don't work with localhost?

Is this true? I'm working on an mvc3 application in visual studio and I want the image I'm using as the header to be a link back to the home page, but since I'm just running it locally I'm using this line as the code:
<a href="localhost:60060">
<img src="../../Content/images/LionLabs.png" alt="Lion logo">
</a>
This doesn't work though! am I doing something wrong, or is it just that localhosts can't be used as this?
I also just tried using a javascript method as the href to refresh the page, but that didn't work either :(
Since links by default start at the domain, there is no reason to specify it. You can just use /.
<a href="/">
<img src="../../Content/images/LionLabs.png" alt="Lion logo">
</a>
HTML links work just fine with localhost:
<a href="http://localhost:60060/">
<img src="../../Content/images/LionLabs.png" alt="Lion logo">
</a>
The issue here is that just using localhost:60060 attempts to use a relative path, so the browser is actually looking for http://localhost:60060/localhost:60060/, which, of course, is an invalid path.
Also, you should not use absolute paths when linking between pages of your application, because that becomes a nightmare when you need to change domain names (like, deploying your application to the web).
To make your code more MVC friendly, do this:
<a href="#Url.Action("Index", "Home")">
<img src="#Url.Content("~/Content/images/LionLabs.png")" alt="Lion logo">
</a>
What's happening here is that the ASP.NET MVC Url helper is supplying the proper path information when the page is served out to the user, so it automatically accommodates any changes in the server. It also allows you to use your Routes to best effect, because you can easily change the route (ie the URL) of a link but still use the same controller and view.
The links for <a href=""> don't differ from the links for <img src=""> .
You shouldn't use absolute path, because, when you deploy your project, the site name will not be localhost:60060.
For main page use
Change this:
<a href="localhost:60060">
<img src="../../Content/images/LionLabs.png" alt="Lion logo">
</a>
To this:
<a href="#Url.Action("Index", "Home")">
<img src="#Url.Content("~/Content/images/LionLabs.png")" alt="Lion logo">
</a>
Why?
It's better to use #Url.Action as that will use any custom routing you set in Global.asax. Can you imagine modifying every single link reference on a complex site if you have to change your url routing? :)
Use #Url.Content, as that will correctly resolve to the root of your application, taking away the uncertainty of using ../ or ../../ or ../../... It's cleaner!
You have used href as localhost:60060. It should be a page (may be default.html or something like that).