簡體   English   中英

AngularJS應用程序:無法更新$ index

[英]AngularJS application: unable to update $index

我正在使用Giphy.com api在AngularJS 1.6中開發應用程序。

有一個Plunker 這里

我迭代了來自https://api.giphy.com/v1/gifs/trending?api_key=myApyKey的一系列“giphys”,並將它們顯示在Bootstrap 4卡中。

有一個視圖單giphy功能 在控制器中我有:

// Create controller for the "giphyApp" module
app.controller("giphyCtrl", ["$scope", "$http", "$filter", "$timeout", function($scope, $http, $filter, $timeout) {
  var url = "https://api.giphy.com/v1/gifs/trending?api_key=PTZrBlrq8h2KUsRMeBuExZ5nHyn7dzS0&limit=120&rating=G";
  $scope.giphyList = [];
  $scope.search = "";
  $scope.filterList = function() {
    var oldList = $scope.giphyList || [];
    $scope.giphyList = $filter('filter')($scope.giphys, $scope.search);
    if (oldList.length != 0) {
      $scope.pageNum = 1;
      $scope.startAt = 0;
    };
    $scope.itemsCount = $scope.giphyList.length;
    $scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
  };

  $http.get(url)
  .then(function(data) {
      // giphy arary
      $scope.giphys = data.data.data;
      $scope.filterList();
      console.log($scope.giphys);

      // Paginate
      $scope.pageNum = 1;
      $scope.perPage = 24;
      $scope.startAt = 0;
      $scope.filterList();

      $scope.currentPage = function(index) {
        $("html, body").animate({
          scrollTop: 0
        }, 500);
        $timeout( function(){
          $scope.pageNum = index + 1;
          $scope.startAt = index * $scope.perPage;
        },0);
      };

      $scope.prevPage = function() {
        if ($scope.pageNum > 1) {
          $scope.pageNum = $scope.pageNum - 1;
          $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
        }
      };

      $scope.nextPage = function() {
        if ($scope.pageNum < $scope.pageMax) {
          $scope.pageNum = $scope.pageNum + 1;
          $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
        }
      };

      $scope.selectedIndex = null;
      $scope.selectedGiphy = null;

      $scope.fetchSinglegGiphy = function(giphy, index) {
        console.log(index);
        $scope.selectedIndex = index;
        $scope.selectedGiphy = giphy;
      }
    });
}]);

網格

<div class="row grid" ng-if="giphyList.length > 0">
  <div data-ng-repeat="giphy in giphyList | limitTo : perPage : startAt" 
       class="col-xs-12 col-sm-6 col-lg-4 col-xl-3 d-flex mb-4">
    <div class="giphy d-flex flex-column w-100">
      <div class="thumbnail pb-2 text-center" data-toggle="modal"
           data-target="#giphyModal"
           ng-click="fetchSinglegGiphy(giphy, $index)">
        <img ng-src="{{giphy.images.downsized.url}}" class="img-fluid">
      </div>
      <div class="text mt-auto">
        <p class="m-0 meta">{{giphy.import_datetime | dateParse | date : "MMMM dd y" }}</p>
        <p class="rating m-0">
          <i class="fa fa-star" aria-hidden="true"></i> {{giphy.rating | capitalize}}
        </p>
        <ul class="list-unstyled mb-0 text-center">
          <li ng-if="giphy.username != ''" class="text-muted">{{giphy.type | capitalize}} file uploaded by
            <br><strong>{{giphy.username | capitalize }}</strong>
          </li>
          <li ng-if="giphy.username == ''" class="text-muted">{{giphy.type | capitalize}} file uploaded by
            <br> <strong>Unknown</strong>
          </li>
          <li class="h6">{{giphy.title | titlecase }}</li>
        </ul>
      </div>
    </div>
  </div>
</div>

模態

<div class="modal fade" id="giphyModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title h-3">{{selectedGiphy.title | titlecase }}</h4>
        <button type="button" class="close" data-dismiss="modal">
        <span>&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-12">
            <div class="image image text-center">
              <img ng-src="{{selectedGiphy.images.original.url}}"
                   alt="{{selectedGiphy.title }}" class="img-fluid">
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer justify-content-between">
        <div class="text-muted">Image ID: {{selectedGiphy.id}}</div>
        <div class="btn-group btn-group-sm">
          <button type="button" class="btn btn-success" data-dismiss="modal">
             <i class="fa fa-times-circle"></i> Close
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

這部分應用程序運行正常。

我本來希望能夠輕松地將下一個和之前的giphy添加到上面的模式中:

<div class="controls text-center">
    <a href="#" ng-click="fetchSinglegGiphy(giphy, $index = $index - 1)" class="left">
      <i class="fa fa-chevron-left"></i>
    </a>
    <a href="#" ng-click="fetchSinglegGiphy(giphy, $index = $index + 1)" class="right">
      <i class="fa fa-chevron-right"></i>
    </a>
</div>

令我驚訝的是,這不起作用。 當我單擊任何一個控件時,GIF文件保持不變,並且模式中的所有文本都會消失。

問題:

  1. 這種方法有什么問題?
  2. 你看到一個可行的選擇嗎?

當我單擊任何一個控件時,GIF文件保持不變

檢查giphy等於你的期望:

$scope.fetchSinglegGiphy = function(giphy, index) {
   $scope.selectedIndex = index;
   $scope.selectedGiphy = giphy;
   if ( giphy != $scope.giphyList[index] ) {
      $scope.selectedGiphy = $scope.giphyList[index];
   };
};

更新selectedGiphy ,如果不是。

你不僅可以在ng-repeat塊之外使用$ index,而且還可以在該塊之外使用giphy,而不是定義它。

我假設您在控制器中定義了$ scope.giphyList。 所以你要做的就是發送索引。

$scope.selectedIndex = null;
$scope.selectedGiphy = null;

$scope.fetchSinglegGiphy = function(index) {
   $scope.selectedIndex = index;
   $scope.selectedGiphy = $scope.giphyList[index];
}
<div class="controls text-center">
    <a href="#" ng-click="fetchSinglegGiphy(selectedIndex-1)" class="left">
      <i class="fa fa-chevron-left"></i>
    </a>
    <a href="#" ng-click="fetchSinglegGiphy(selectedIndex+1)" class="right">
      <i class="fa fa-chevron-right"></i>
    </a>
</div>

干杯,我希望這會有所幫助

的index.html

<div class="modal fade" id="giphyModal">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="controls text-center">
            <a href="#" ng-click="fetchSinglegGiphyModal('prev')" class="left"><i class="fa fa-chevron-left"></i></a>
            <a href="#" ng-click="fetchSinglegGiphyModal('next')" class="right"><i class="fa fa-chevron-right"></i></a>
         </div>
         <div class="modal-header">
            <h4 class="modal-title h-3">
               {{ selectedGiphy.title | capitalize }}
            </h4>
            <button type="button" class="close" data-dismiss="modal">
               <span>&times;</span>
            </button>
         </div>
         <div class="modal-body">
            <div class="row">
               <div class="col-12">
                  <div class="image image text-center">
                     <img ng-src="{{ selectedGiphy.images.original.url }}" alt="{{ selectedGiphy.title }}" class="img-fluid" image-on-load ng-hide="modalImageLoading" />
                     <div class="spinner-border" ng-if="modalImageLoading"></div>
                  </div>
               </div>
            </div>
         </div>
         <div class="modal-footer justify-content-between">
            <div class="text-muted">
               Image ID: {{ selectedGiphy.id }}
            </div>
            <div class="btn-group btn-group-sm">
               <button type="button" class="btn btn-success" data-dismiss="modal">
                  <i class="fa fa-times-circle"></i> Close
               </button>
            </div>
         </div>
      </div>
   </div>
</div>

改進:

<a href="#" ng-click="fetchSinglegGiphyModal('prev')" class="left"><i class="fa fa-chevron-left"></i></a>
<a href="#" ng-click="fetchSinglegGiphyModal('next')" class="right"><i class="fa fa-chevron-right"></i></a>

fetchSinglegGiphyModal根據作用於我們在函數中傳遞的參數prevnext值的條件處理前一個和下一個Giphy

我還添加了以下代碼來介紹帶有引導程序的加載程序,以指示GIF圖像正在后台加載。

<div class="image image text-center">
   <img ng-src="{{ selectedGiphy.images.original.url }}" alt="{{ selectedGiphy.title }}" class="img-fluid" image-on-load ng-hide="modalImageLoading" />
   <div class="spinner-border" ng-if="modalImageLoading"></div>
</div>

app.js

$scope.modalImageLoading = false;

$scope.fetchSinglegGiphy = function (giphy, index) {
   $scope.selectedIndex = index;
   $scope.selectedGiphy = giphy;
   $scope.modalImageLoading = true;
};

$scope.fetchSinglegGiphyModal = function (dir) {
   let selectedGiphy = null;
   if (dir === "prev") $scope.selectedIndex -= 1; // To load previous
   else if (dir === "next") $scope.selectedIndex += 1; // To load next

   selectedGiphy = $scope.giphyList[$scope.selectedIndex];
   if (selectedGiphy) {
      $scope.selectedGiphy = selectedGiphy;
      $scope.modalImageLoading = true;
   }
};

$scope.fetchSinglegGiphyModal作用於我們在參數中傳遞的條件並顯示相應的Giphy數據。

我已經實現了一個自定義指令來顯示圖像元素並在下載圖像時隱藏加載器。 這是指令代碼:

app.directive('imageOnLoad', function () {
   return {
      restrict: 'A',
      controller: 'giphyCtrl',
      link: function (scope, element, attrs) {
         element.bind('load', function () {
            scope.$apply(function () {
               scope.modalImageLoading = false;
            });
         });
      }
   }
});

這是修改后的plunker 代碼

希望能幫助到你!

如果你將giphy移動到模態,你也應該發送$ index(就像你真的那樣),所以在模態中你知道你的索引是誰,而不管$ index。

<div class="controls text-center">
    <a href="#" ng-click="fetchSinglegGiphy(giphy, selectedIndex - 1)" class="left"><i class="fa fa-chevron-left"></i></a>
    <a href="#" ng-click="fetchSinglegGiphy(giphy, selectedIndex + 1)" class="right"><i class="fa fa-chevron-right"></i></a>
 </div>

暫無
暫無

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

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