Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs if statement in ng-href

I have some elements which are created dynamically and every element has a different ng-href.

I want to give different link according to some elements.

When I try to write function in ng-href it sends the page to function in url,therefore it does not work.

I try to do something like this;

       .......
             <a 
            ng-href='if(m){#linkOne} else {#linkTwo}'
            ng-click='test(type);'>

              </a> 
       .......

Which method should i use to create element with different ng-href?

like image 690
user4773604 Avatar asked Apr 27 '15 06:04

user4773604


People also ask

How do I bind a href in AngularJS?

The ng-href directive overrides the original href attribute of an <a> element. The ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.

Can we use ngIf in anchor tag?

Can we use ngIf in anchor tag? Descriptionlink. A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.

How does ng-if works?

Definition and Usage. The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

Does ngIf work on Div?

The Angular ngIf directive works essentially as an if statement for HTML, adding this missing feature to the language under the form of the special ngIf attribute. In this example, the container div will only be shown to the user if the user is logged in, otherwise the whole content of the div is not visible.


3 Answers

You can try this

<a ng-href="{{m ? '#linkOne':'#linkTwo'}}" ng-click="test(type)">your link</a>

http://jsfiddle.net/54ema4k0/

like image 55
FDisk Avatar answered Sep 18 '22 15:09

FDisk


Just do like this its very simple.

<a href="{{variable == value ? '#link1' : '#link2'}}">Link</a>
like image 36
Jobincs Avatar answered Sep 19 '22 15:09

Jobincs


You need to use a variable for the link

<a ng-href='{{link}}' ng-click='test(type);'> your link </a>

then

$scope.$watch('m', function(value){
    $scope.link = value ? 'link1': 'link2';
})

Demo: Fiddle

like image 34
Arun P Johny Avatar answered Sep 19 '22 15:09

Arun P Johny