programing

ng-ife ng-repeat 값이 배열에 있는지 확인합니다.

codeshow 2023. 3. 13. 20:41
반응형

ng-ife ng-repeat 값이 배열에 있는지 확인합니다.

API에서 검색된 와인 목록을 반복하는 ng 반복이 있습니다.데이터베이스에서 가져온 즐겨찾기에 추가된 모든 와인 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()를 처음 접하기 때문에 그게 문제인 것 같습니다.하지만 내가 틀렸을지도 몰라.

각도 필터의 포함 필터를 사용할 수 있습니다.

<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를 사용하여 보다 우아하게 수행할 수 있습니다.

와인이 있는 오브젝트(ids를 키)가 있는 경우 매번 인덱스로 검색하는 대신 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을 반환합니다.정정해 주셔서 감사합니다.난 계속 켜져있었어!>

언급URL : https://stackoverflow.com/questions/30059123/check-if-value-is-in-array-for-ng-if-within-ng-repeat

반응형