如果在ng-repeat内,检查值是否在ng-array中

Wil*_*rim 24 javascript angularjs

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

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>
Run Code Online (Sandbox Code Playgroud)

这是我的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);
            });
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

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

fra*_*acz 28

您可以使用angular-filter的包含过滤器:

<span ng-if="favorites | contains:wine.Id">Added</span>
Run Code Online (Sandbox Code Playgroud)

或编写自己的过滤器,做同样的事情:

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


Art*_*ian 12

我建议你将这个逻辑移到控制器上,让你的视图尽可能干净:

   $scope.isFavorites = function(id) {
       return $scope.favorites.indexOf(id) !== -1;
   }
Run Code Online (Sandbox Code Playgroud)

你的观点应该是:

<!-- 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="!isFavorites(wine.Id)">Add</a>
<!-- Else Display Already Added -->
<span ng-if="isFavorites(wine.Id)>Added</span>
Run Code Online (Sandbox Code Playgroud)


Ced*_*Ced 6

我想你必须改变

favorites.indexOf(wine.Id) !> -1
Run Code Online (Sandbox Code Playgroud)

favorites.indexOf(wine.Id) < 0
Run Code Online (Sandbox Code Playgroud)