在AngularJS中使用三元组和href

时间:2016-04-19 05:28:24

标签: html angularjs ternary-operator

如果type=1,那么我希望网址使用变量{{vm.firstPath}}。 对于其他任何事情,它应该使用{{vm.secondPath}}

这是否可以使用三元组?

当我尝试这样做时,无法识别:

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

3 个答案:

答案 0 :(得分:3)

为此,您应该使用ng-href而不是href。

 <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/

答案 1 :(得分:2)

您可以使用ng-if指令。试试这样:

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

答案 2 :(得分:-1)

您需要更改此类代码 -

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

或者 -

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