【问题标题】:How to display the count of all items on click of a button in AngularJS?如何在单击AngularJS中的按钮时显示所有项目的计数?
【发布时间】:2018-01-19 01:00:13
【问题描述】:

我说轮播上有 9 个项目。

我想在轮播图片下方显示单个项目的数量。

我创建了一个 Plunker 来演示这个问题。

Plunker Link

HTML 代码

<head>
<script data-require="angular.js@1.2.19" data-semver="1.2.19" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js">
</script>
<script data-require="jquery@2.1.1" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="http://vasyabigi.github.io/angular-slick/bower_components/slick-carousel/slick/slick.css" />
<script src="http://vasyabigi.github.io/angular-slick/bower_components/slick-carousel/slick/slick.js"></script>
<script src="angular-slick.js"></script>
<script src="script.js"></script>
</head>

<body ng-controller="appController">
<h1>Hello Plunker!</h1>
<button type="button" ng-click="showCount()">Show count of all items</button>

<slick ng-if="dataLoaded" init-onload="false" data="dataLoaded" slides-to-show="3" dots="true">
  <div ng-repeat="item in items">
    <span>
        <img ng-src="{{ item.imgSrc }}" alt="{{ item.catId}}" />
    </span>
    <span>{{ item.catId }}</span>
  </div>
</slick>

JS 代码

var app = angular.module("slick-example", ["slick"]);
app.controller('appController', function($scope, $timeout) {
    $scope.items = [];
    // simulate that the data is loaded from a remote source
    $timeout(function() {
        $scope.items = [{
            imgSrc: 'http://placekitten.com/325/325',
            catId: '1'
        }, {
            imgSrc: 'http://placekitten.com/g/325/325',
            catId: '2'
        }, {
            imgSrc: 'http://placekitten.com/325/325',
            catId: '3'
        }, {
            imgSrc: 'http://placekitten.com/g/325/325',
            catId: '4'
        }, {
            imgSrc: 'http://placekitten.com/325/325',
            catId: '5'
        }, {
            imgSrc: 'http://placekitten.com/g/325/325',
            catId: '6'
        }, {
            imgSrc: 'http://placekitten.com/325/325',
            catId: '7'
        }, {
            imgSrc: 'http://placekitten.com/g/325/325',
            catId: '8'
        }, {
            imgSrc: 'http://placekitten.com/325/325',
            catId: '9'
        }];
        $scope.countItem = [{
            "catId": 1,
            "availableCount": 2
        }, {
            "catId": 2,
            "availableCount": 3
        }, {
            "catId": 3,
            "availableCount": 4
        }, {
            "catId": 4,
            "availableCount": 2
        }, {
            "catId": 5,
            "availableCount": 1
        }, {
            "catId": 6,
            "availableCount": 5
        }, {
            "catId": 7,
            "availableCount": 3
        }, {
            "catId": 8,
            "availableCount": 2
        }, {
            "catId": 9,
            "availableCount": 1
        }];
        // update the dataLoaded flag after the data has been loaded
        // i dont know why but its important that the flag doesnt get initialized in an previous step like $scope.dataLoaded = false;
        $scope.dataLoaded = true;
    }, 2000);
    $scope.showCount = function() {}
});

单击按钮(按钮 - 显示单个项目的计数)时,我试图在轮播中的每个图像下方显示单个项目的计数,但我无法找到这样做的方法。单击按钮时将显示所有项目的计数

请参考 Plunker(我只使用 AngularJS 和 vanilla JS,没有 Jquery)

请帮助我如何在每张图片下方显示轮播中单个项目的数量

【问题讨论】:

  • 你想把 countItem 和 items 关联起来吗?
  • @ Jesus Carrasco 是计数或数量 - 您更喜欢这两个术语中的任何一个?但我必须同时在轮播图像下方的 div 中显示计数/数量
  • @Jesus Carrasco 我必须显示单个项目的数量,比如项目 1 的数量是 2,而项目 2 的数量是 4,我必须在每张图片下方显示这个单独的数量
  • 好的,我知道你需要根据 catId 混合两个 json
  • @Jesus Carrasco 我不想混合 json 。是否可以保持 2 json 不变?

标签: javascript html css angularjs angularjs-scope


【解决方案1】:

这里有两种方法,第二种基于评论信息。

版本不修改数组

这个版本会等到数据“加载”完毕,然后会创建一个地图,该地图将用于 HTML 中计数的插值。

HTML

此按钮将打开/关闭计数:

<button type="button" ng-click="showCount = !showCount">Toggle Count</button>

这将转到您要在 ng-repeat 中显示计数的位置:

<span ng-if="showCount">Count of Items: {{ countMap[$index] }}</span>

有关$index 的更多信息,请查看ng-repeat 上的文档。基本上,它会告诉您当前重复元素的来源数组中的索引(位置)。

JS

在控制器的根目录中:

  // Create a mapping of array position : count
  $scope.countMap = {};

这使我们以后可以轻松地查找数据。例如:

$scope.countMap1 = '你好'; console.log($scope.countMap1); // -> 你好

然后,在你的 $timeout 之后,一旦它解决(意味着超时,http 请求完成等):

$timeout(function() {
   // Abbreviated, not including items.

  }, 2000).then(function() {
    // After resolve, assuming you are calling an API in real implementation

    // Iterate through the returned items, and add the count
    // to the array pos : count mapping
    for (var i = 0; i < $scope.items.length; i++) {
      $scope.countMap[i] = getCountFor($scope.items[i].catId);
    }

  });

** 另外值得注意的是**,你设置了$scope.dataLoaded = true,但它在超时之内。它应该移动到.then(function() {} 以确保在promise 解决之前不会设置它。

然后,下面修改版本的原始 getCountFor(id) 函数:

  function getCountFor(id) {
    for (var i = 0; i < $scope.countItem.length; i++) {
      if ($scope.countItem[i].catId == id) {
        return $scope.countItem[i].availableCount;
      }
    }
  }

https://plnkr.co/edit/UOY7WONh6TUCBRrZYnvZ?p=preview

版本修改数组

这应该可以解决问题。当您单击“显示计数...”时,该函数将遍历 $scope.items 中的每个 cat 对象,并调用 getCountFor(id) 并附加通过关联每个数组中对象的 catId 找到的 availableCount 值。

HTML

  <div ng-repeat="item in items">
    <span>
        <img ng-src="{{ item.imgSrc }}" alt="{{ item.catId}}" />
    </span>
    <span>{{ item.catId }}</span>
    <span> Count of Items: {{ item.availableCount }}</span>
  </div>

JS

这是一个用于分离代码关注点的函数。它将id 作为参数。然后它递增 i,从 0 开始,直到 i 的值是 $scope.countItem 数组的长度。对于数组中的每个位置,都有一个项目。如果传递给函数的id 的值与数组中位置i 的对象的catId 的值匹配,则返回可用计数的值。

  function getCountFor(id) {
    for (var i = 0; i < $scope.countItem.length; i++) {
      if ($scope.countItem[i].catId == id) {
        return $scope.countItem[i].availableCount;
      }
    }
  }

此函数位于$scope,因为它是从您的 UI 调用的。调用时,它会遍历$scope.items 中的每个项目,并在该项目上设置一个名为availableCount 的新属性。它会将$scope.items 中的每个项目呈现为如下所示:

{
    imgSrc: 'http://placekitten.com/325/325',
    catId: '1',
    availableCount: 0
}

以及实际的 showCount() 函数:

  $scope.showCount = function() {
    $scope.items.forEach(function(item) {
      item.availableCount = getCountFor(item.catId);
    })
  }

https://plnkr.co/edit/2uLdLgVtsjbT6v4R0DWi?p=preview

【讨论】:

  • 我必须显示单个项目的数量,比如项目 1 的数量是 2,而项目 2 的数量是 4,我必须在每个项目下方显示这个东西
  • 它的工作。你能帮我理解你的JS代码吗?我只是一个初级程序员
  • 但我不想合并 2 个 json
  • 我创建了一个不修改数组的新版本,而是使用字典。
【解决方案2】:

您需要遍历项目以找到位于另一个数组中的 idCat。和子循环,查找匹配id,获取availableCount。

您需要在 showCount 函数中执行此操作

HTML 显示所有项目的计数

<slick ng-if="dataLoaded" init-onload="false" data="dataLoaded" slides-to-show="3" dots="true">
  <div ng-repeat="item in itemsCopy">
    <span>
        <img ng-src="{{ item.imgSrc }}" alt="{{ item.catId}}" />
    </span>
    <span>{{ item.catId }} {{ 'count: '+ item.availableCount }}</span>
  </div>
</slick>

控制器

$scope.showCount = function(){

 $scope.itemsCopy = $scope.item;

angular.forEach($scope.itemsCopy, function(value, index){

    for(var i = 0; i < $scope.countItem.length; i++){
      console.log(value, $scope.countItem[i].catId);
      if(parseInt(value.catId) === $scope.countItem[i].catId ){
        value.availableCount = $scope.countItem[i].availableCount
      } 
    }
});
console.log($scope.itemsCopy);
};

当点击按钮时,计数将显示计数。

我放了一个 plknr 的例子: sample

【讨论】:

  • 它的工作。你能帮我理解你的JS代码吗?我只是一个初级程序员
  • 你合并了2个json吗?我想保持 2 json 完整,我不想合并它们
  • 他们不合并只将属性 availableCont 添加到项目。取而代之的是,您可以为项目制作副本。并在 ng-repeat 中复制。
  • 我无法获得您的最后一份声明。能详细点吗?
  • 我无法获得您的最后一份声明。能详细点吗?
【解决方案3】:

你可以在点击时准备一个这样的数组:

 $scope.showCount = function(){

  angular.forEach($scope.countItem,function(val,key){
    $scope.count[val.catId] = val.availableCount;
  });

}

working plunkar link

【讨论】:

  • 我必须显示单个项目的数量,比如项目 1 的数量是 2,而项目 2 的数量是 4,我必须显示这个东西
  • @Brian thanx :-)
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多