【问题标题】:multiple expression if else within ng-repeatif else 在 ng-repeat 中的多个表达式
【发布时间】:2015-03-21 17:17:23
【问题描述】:
<div ng-repeat="book in books">
<a href="#/{{book.title}}"> <h3 class="title">{{book.title}}</h3></a>
</div>

我使用上面的代码来获取,它工作正常,但我还有一个搜索功能,它也会设置$scope.books。不幸的是,我无法控制 api,搜索回调返回了不同的方案,这意味着要获取我必须导航到其他地方的书名,例如 book.category.item.title

所以我正在考虑做这样的事情

<a href="#/{{book.title || book.category.item.title}}">

检查是否设置了 book.title,否则显示另一个表达式。对吗?

【问题讨论】:

  • 当你想要动态 URL 时使用ng-href。我看不出为什么你正在做的事情不应该工作。你有问题吗?

标签: javascript angularjs


【解决方案1】:

我更喜欢使用ng-href

<a ng-href="{{getTitle()}}">link</a>

在您的控制器中,通过检查那里的逻辑返回url

angular.module("app",[])
   .controller("MainCtrl", function($scope) {
      $scope.book = {};
      $scope.book.title = null;
      $scope.book.category = {
        item : {
          title : "Rafi"
        }
      }
      $scope.getTitle = function() {
        return '#/'+ ($scope.book.title || $scope.book.category && $scope.book.category.item && $scope.book.category.item.title);
      }
    });

DEMO

如果您出于某种原因不想使用控制器:

 <a ng-href="{{'#/'+(book.title || book.category.item.title)}}">

【讨论】:

  • 如果 book.title 为空,将使用 book.title
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 2019-09-04
相关资源
最近更新 更多