簡體   English   中英

如果在ng-repeat內,檢查值是否在ng-array中

[英]Check if value is in array for ng-if within ng-repeat

我有一個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>

這是我的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的包含過濾器

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

或編寫自己的過濾器,做同樣的事情:

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

我建議你將這個邏輯移到控制器上,讓你的視圖盡可能干凈:

   $scope.isFavorites = function(id) {
       return $scope.favorites.indexOf(id) !== -1;
   }

你的觀點應該是:

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

我想你必須改變

favorites.indexOf(wine.Id) !> -1

favorites.indexOf(wine.Id) < 0

favorites.indexOf(wine.Id) !> -1看起來不像是一個合適的角度表達式。 請注意,當您在模板中使用表達式時,只允許使用一些基本的javascript條件。 請參閱文檔以了解可能的內容。

而不是列出所有葡萄酒和最喜歡的葡萄酒列表,你最好擴大名單,所有葡萄酒的布爾屬性isFavorite 這對於性能也更好,因為它不需要在每次迭代中在第二個列表中搜索葡萄酒。

在響應回調循環(快速和臟):

var index = $scope.favorites.indexOf(r.id);
if(index > -1) {
  $scope.favorites[index].isFavorite = true;
} // else isFavorite is undefined, which is falsy

像這樣的數組操作可以做到更優雅下划線Lodash

請注意,如果您有一個帶有葡萄酒的對象(ID為關鍵),則可以通過id檢索葡萄酒,而不是每次都通過索引查找。 ngRepeat像數組一樣支持對象。

在您的模板中:

<!-- 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="!wine.isFavorite"> Add </a>
<!-- Else Display Already Added -->
<span ng-if="wine.isFavorite">Added</span>

!>無效。 只能與=一起使用,或者使用布爾值。 使用

favorites.indexOf(wine.Id) == -1

如果indexOf無法在數組中找到該元素,則返回-1。 謝謝你的糾正。 我被困住了!>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM