【问题标题】:clicking on a specific ion-item button triggers other buttons单击特定的离子项目按钮会触发其他按钮
【发布时间】:2017-09-29 11:36:00
【问题描述】:

我使用 ng-repeat 生成一个离子列表。每个 ion-item 内部都有一个切换行为按钮,当点击和取消点击时会改变颜色。但是,当我点击一个离子项目中的按钮时,其他离子项目的其他按钮也会被点击并改变它们的颜色。我该怎么办?

<ion-list id="listOfCandidates-list6">
  <ion-item ng-repeat="item in itemList" class="item-candidates alternaterow item-thumbnail-left" id="listOfCandidates-list-item8">
   <img src="img/tRk31wFSmS2hKHXnIAOZ_candidateicon.png">
   <br>
    <div class="col1">
    <h4>Name: {{item.name}}</h4><h4>Candidate No.: {{item.number}}</h4>
    </div>
    <div class="col2">
    <button class="button button-clear icon ion-star button-energized" ng-model="singleTog" ng-click="toggleButton(item.name)" ng-class="singleTog.clicked?'button-energized':'button-dark'" ></button>
    <button ng-click="goDetail(item.name,item.number)" class="button btn-small btn-primary">View</button>
    </div>
  </ion-item>
</ion-list>

这是我的 controller.js 代码:

$scope.favoriteList = []
$scope.singleTog = {}

$scope.toggleButton = function(candidateName)
{
 $scope.singleTog.clicked=!$scope.singleTog.clicked
 if($scope.singleTog.clicked==true)
 {
   if($scope.favoriteList.indexOf(candidateName) == -1) //does not exist in array
   {
    $scope.favoriteList.push(candidateName);
   }
 }
 else
 {
   if($scope.favoriteList.indexOf(candidateName) != -1) //exists in array
   {
     var index = $scope.favoriteList.indexOf(candidateName);
     $scope.favoriteList.splice(index, 1);   
   }
 }

 alert('favorites = ' + $scope.favoriteList);
}

【问题讨论】:

  • 您在 ng-repeat 中的项目都被绑定到您的 ng-model 指令中定义的同一个对象实例。

标签: angularjs ionic-framework


【解决方案1】:

将索引传递给您正在调用的函数以触发事件。

<button class="button button-clear icon ion-star button-energized" ng-model="singleTog" ng-click="toggleButton(item.name,$index)" ng-class="singleTog[$index] ?'button-energized':'button-dark'" ></button>
<button ng-click="goDetail(item.name,item.number)" class="button btn-small btn-primary">View</button>

在你的控制器中

$scope.singleTog =[];

$scope.toggleButton = function(candidateName,index)
{
$scope.singleTog[index]=!$scope.singleTog[index];
 if($scope.singleTog[index])
 {
   if($scope.favoriteList.indexOf(candidateName) == -1) //does not exist in array
   {
    $scope.favoriteList.push(candidateName);
   }
 }
 else
 {
   if($scope.favoriteList.indexOf(candidateName) != -1) //exists in array
   {
     var index = $scope.favoriteList.indexOf(candidateName);
     $scope.favoriteList.splice(index, 1);   
   }
 }
alert('favorites = ' + $scope.favoriteList);

}

【讨论】:

  • 嗨,感谢您的意见。它可以工作,但是我只能选择一个项目,有没有办法能够单击多个按钮而不影响其他按钮?
  • 你能详细说明你的具体要求是什么
  • 列表中每个项目的按钮在单击后必须变为黄色,然后在再次单击相同按钮后变回黑色。此外,它应该能够点击多个按钮......这有点像每个可以选择和取消选择的项目都有一个复选框。
  • 我只是对现有代码做了一些修改。希望对你有帮助
猜你喜欢
  • 1970-01-01
  • 2020-01-18
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 2019-12-07
  • 2012-02-25
相关资源
最近更新 更多