我有一个 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/