Javascript 检查值是否在 ng-repeat 中的 ng-if 数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30059123/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value is in array for ng-if within ng-repeat
提问by Wil Prim
I have an ng-repeat looping through a list of wines retrieved from an API. I also have a array variable containing all wine ids that have been added to favorites fetched from database. I want to be able to display an "Add To Favorites" button if the user has not yet added a specific result wine from the list. To do this I thought I would do something like:
我有一个 ng-repeat 循环遍历从 API 检索到的葡萄酒列表。我还有一个数组变量,其中包含已添加到从数据库获取的收藏夹中的所有葡萄酒 ID。如果用户尚未从列表中添加特定的结果酒,我希望能够显示“添加到收藏夹”按钮。为此,我想我会做类似的事情:
HTML:
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>
Here is my JS:
这是我的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);
            });
        });
    };
});
I am new to .indexOf() so I am thinking maybe that is the problem. But Maybe I am wrong.
我是 .indexOf() 的新手,所以我想也许这就是问题所在。但也许我错了。
回答by fracz
You can use angular-filter's containsfilter:
您可以使用angular-filter 的contains过滤器:
<span ng-if="favorites | contains:wine.Id">Added</span>
or write your own filter that does the same:
或者编写自己的过滤器来做同样的事情:
angular.module('module').filter('contains', function() {
  return function (array, needle) {
    return array.indexOf(needle) >= 0;
  };
});
回答by Artem Petrosian
I would recommend you to move this logic to controller an keep your view as clean as possible:
我建议您将此逻辑移至控制器以尽可能保持您的视图清洁:
   $scope.isFavorites = function(id) {
       return $scope.favorites.indexOf(id) !== -1;
   }
And your view should be:
你的观点应该是:
<!-- 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>
回答by Ced
I think you have to change
我认为你必须改变
favorites.indexOf(wine.Id) !> -1
into
进入
favorites.indexOf(wine.Id) < 0
回答by Frank van Wijk
favorites.indexOf(wine.Id) !> -1does not look like a proper angular expression. Note that when you have expressions in your templates, only some basic javascript conditionals are allowed. See the docsfor what is possible.
favorites.indexOf(wine.Id) !> -1看起来不像一个合适的角度表达式。请注意,当您的模板中有表达式时,只允许使用一些基本的 javascript 条件。有关可能的内容,请参阅文档。
Instead of having a list of all wines and a list with favorite wines, you better extend the list with all wines with a boolean property isFavorite. This is also better for performance, since it does not need to search for the wine in the second list every iteration.
与其拥有所有葡萄酒的列表和最喜欢的葡萄酒的列表,不如将列表扩展为包含布尔属性的所有葡萄酒isFavorite。这对性能也更好,因为它不需要每次迭代都在第二个列表中搜索酒。
In the reponse callback loop (quick and dirty):
在响应回调循环中(又快又脏):
var index = $scope.favorites.indexOf(r.id);
if(index > -1) {
  $scope.favorites[index].isFavorite = true;
} // else isFavorite is undefined, which is falsy
Array operations like this can be done more elegantly with Underscoreor Lodash.
Note that if you have an object with wines (ids as key), wines can be retrieved by id instead of lookup by index every time. ngRepeatsupports objects just like arrays.
请注意,如果您有一个带有 wine 的对象(以 id 作为键),则可以通过 id 检索 wine,而不是每次都通过索引查找。ngRepeat像数组一样支持对象。
In your template:
在您的模板中:
<!-- 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>
回答by Pratik
!> is not valid. ! can only be used with =, or with a boolean value. Use
!> 无效。!只能与 = 或布尔值一起使用。用
favorites.indexOf(wine.Id) == -1
indexOf returns -1 if it can't find the element in the array. Thanks for the correction. I was stuck on !>
如果 indexOf 找不到数组中的元素,则返回 -1。谢谢指正。我被卡住了!>

