在 AngularJS 中将三元与 href 结合使用

Using ternary with href in AngularJS

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

这可以使用三元组吗?

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

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

您需要像这样更改代码-

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

为此,您应该使用 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/

您可以使用 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>