1

If type=1, then I want the url to use the variable {{vm.firstPath}}. For anything else it should use {{vm.secondPath}}.

Is this doable using a ternary?

When I tried doing this it is not recognised:

{{type==1? <a href="{{vm.firstPath}}">{{vm.name}}</a> : <a href="{{vm.secondPath}}">{{vm.name}}</a>}}

3 Answers 3

3

You should use ng-href istead of href for this purpose.

 <a ng-href="type == 1 ? 'http://www.google.com' : 'http://www.facebook.com'">Link</a>

var app = angular.module('foo', [])


app.controller('main', function($scope){

    $scope.type = 1;

})

JsFiddle : http://jsfiddle.net/nikdtu/b910258t/

Sign up to request clarification or add additional context in comments.

2 Comments

In the fiddle, I see a link containing the expression, not its result: <a ng-href="type == 1 ? 'http://www.google.com' : 'http://www.facebook.com'" href="type == 1 ? 'http://www.google.com' : 'http://www.facebook.com'">Link</a>
This is not working now, its not working in the fiddle too.!
3

you can use ng-if directive. try like this:

    <a ng-if="type==1" ng-href="{{vm.firstPath}}">{{vm.name}}</a>
    <a ng-if="type !=1" ng-href="{{vm.secondPath}}">{{vm.name}}</a>

Comments

0

You need to change code like this-

<a href="{{type==1?vm.firstPath:vm.secondPath}}">{{vm.name}}</a> 

Or-

<a href="{{vm.firstPath}}" ng-if="type==1">{{vm.name}}</a> 
<a href="{{vm.secondPath}}" ng-if="type!=1">{{vm.name}}</a>

3 Comments

This won't work is some cases. Read more about href and ng-href @ docs.angularjs.org/api/ng/directive/ngHref
Not sure why you did't get that. Anyway, If you want to use AngularJS markup inside your links, you have to use ng-href instead of href. The reason is that it takes time for AngularJS to parse all HTML, and this means that if the user is quick he/she can click the link before it is actually parsed. This would result in a 404-page. So, instead of writing this: <a href="someurl.com{{hash}}"/> you should write this: <a ng-href="someurl.com{{hash}}"/> Read pterkildsen.com/2012/11/16/angularjs-tips-and-tricks for more insight.
Yes, that's a valid reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.