Reputation: 9285
I have a link that should call a $scope-function which causes another view to bei displayed.
But I also want that the User can rightclick onto that Link and open it into a new window or bookmark this.
So this is the (non-working) html:
<a ng-click="OpenSubsite(singleitem.Id)" href="{{GetUrl(singleItem.Id)}}">{{singleItem.Title}}</a>
The controller contains the following Code:
$scope.OpenSubSite=function(id) {
$scope.LoadItem(id);
}
$scope.GetUrl=function(id) {
return "showitem.html#id="+id;
}
Both methods alone work fine. Just not in the combination I want. I want the "OpenSubSite()
" to be called when clicking onto that URL but when doing a rightclick ("open in new tab" or "add to favorites") the "GetUrl()
"-Returnvalue should be used instead.
But with this code, the URL from GetUrl() is always opened even on left Mousebutton click,
Is there a way to make this happen?
Upvotes: 2
Views: 8649
Reputation: 10783
An alternative answer: You can get $event
in ng-method and determine which button is clicked. After that, you can assign any method to related button like this:
var app = angular.module('app', []).controller('controller', function ($scope, $http) {
/*
other methods like LoadItem
*/
$scope.LoadItem = function(id) {
//some stuf here
}
$scope.OpenSubSite=function(id) {
$scope.LoadItem(id);
};
$scope.GetUrl=function(id) {
return "showitem.html#id="+id;
};
$scope.handleClick = function(evt, id) {
evt.preventDefault();
switch(evt.which) {
case 1:
alert("left click");
$scope.OpenSubSite(id);
// this is left click
break;
case 3:
alert("right click");
$scope.GetUrl(id);
// this is right click
break;
default:
break;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="controller">
<a href="#" ng-mousedown="handleClick($event, 1)">link</a>
</div>
</div>
Upvotes: 0
Reputation: 1808
Just add onclick="return false;"
the html will be
<a ng-click="OpenSubsite(singleitem.Id)" onclick="return false;" href="{{GetUrl(singleItem.Id)}}">{{singleItem.Title}}</a>
this will prevent the clicking to redirect to GetUrl but it will work in case you use open in new tab
Upvotes: 1
Reputation: 171679
you need to prevent the default
ng-click="OpenSubsite($event,singleitem.Id)"
$scope.OpenSubSite=function($event,id) {
$event.preventDefault()
$scope.LoadItem(id);
}
Upvotes: 1
Reputation: 13997
You have to prevent the default action when you trigger the ng-click
. You can do that by passing the $event
object of the ng-click
directive:
<a ng-click="OpenSubsite($event, singleitem.Id)">..</a>
Then in the controller:
$scope.OpenSubSite = function(ev, id) {
ev.preventDefault(); // prevent it opens default
$scope.LoadItem(id);
return false;
}
Upvotes: 2