javascript - 检查值是否在 ng-repeat 内 ng-if 的数组中

标签 javascript angularjs

我有一个 ng-repeat 循环遍历从 API 检索的 Wine 列表。我还有一个数组变量,其中包含已添加到从数据库获取的收藏夹中的所有 Wine ID。如果用户尚未从列表中添加特定的结果酒,我希望能够显示“添加到收藏夹”按钮。为此,我想我会这样做:

HTML:

<tr ng-repeat="wine in wines">
    <td>{{$index+1}}</td>
    <td>{{ wine.Name }}</td>
    <td>{{ wine.Appellation.Name }}</td>
    <td>${{ wine.PriceMin }} - ${{ wine.PriceMax }}</td>
    <td>
        <!-- If wine.Id is not yet in the array of all favorite ids, display "Add Button" -->
        <a href="#" class="btn btn-primary btn-dark" ng-click="addToFavorites(wine.Id)" ng-if="favorites.indexOf(wine.Id) !> -1"> Add </a>
        <!-- Else Display Already Added -->
        <span ng-if="favorites.indexOf(wine.Id) > -1">Added</span>
    </td>
</tr>

这是我的 JS:

app.controller("MainController", function($scope, $http){
    $scope.favorites = [];
    var getAllFavorites = function(){
        $http.get("/home/getAllFavoriteIds").success(function(response) {
            angular.forEach(response, function(r) {
                $scope.favorites.push(r);
            });
        });
    };
});

我是 .indexOf() 的新手,所以我想这可能就是问题所在。但也许我错了。

最佳答案

您可以使用angular-filter's contains filter :

<span ng-if="favorites | contains:wine.Id">Added</span>

或者编写您自己的过滤器来执行相同的操作:

angular.module('module').filter('contains', function() {
  return function (array, needle) {
    return array.indexOf(needle) >= 0;
  };
});

关于javascript - 检查值是否在 ng-repeat 内 ng-if 的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059123/

相关文章:

javascript - 检查数组中的对象值是否已经存在于不同的对象数组中?

javascript - 如何在用户向下滚动到内容时加载内容?

javascript - 如何将 crypto.WordArray 转换为 Uint8Array?

javascript - 如何在没有外部库的情况下在 React 中实现 Google Maps JS API?

javascript - 运行终端应用程序时出现意外的 token 导出

javascript - Angular,过滤 json 对象

angularjs - 如何在 Google Apps 脚本中使用 AngularJS 与服务器通信

javascript - 防止 Angular Material md-tab 中的制表符更改事件

javascript - 在 Angular JS 模板中,在父元素之间交替,同时保持子元素完整

javascript - ng-mouseover 和 ng-show 不起作用