【问题标题】:Change one button(element) in ng-repeat在 ng-repeat 中更改一个按钮(元素)
【发布时间】:2017-04-10 22:11:42
【问题描述】:

我有一个表格,它是根据 API 调用的响应构建的,因此使用 ng-repeat 来显示所有元素。

这个想法是应该有一个“播放按钮”供用户单击,然后播放一个简短的音频剪辑。当用户单击播放按钮时,该按钮应变为“暂停按钮”,用户可以单击该按钮暂停音频。

我的问题是,当按钮从“播放”变为“暂停”时,它会在表格的所有行中发生变化(而不仅仅是我点击播放按钮的那一行)。

这就是它在我的 HTML 中的样子:

<tr ng-repeat="r in results">
...
   <i ng-show="playButton" ng-click="playedPreview(false)" class="material-icons small play" style="cursor:pointer;">play_circle_outline</i>

   <i ng-show="!playButton" ng-click="playedPreview(true)" class="material-icons small pause" style="cursor:pointer;">pause_circle_outline</i> 
...
</tr>

在我的控制器中:

$scope.playedPreview = function(state) {
    $scope.playButton = state;
    console.log($scope.playButton);
}

我很快意识到为什么我的按钮在所有行中都发生了变化,但我不知道应该如何强制它只在一行中发生变化。

我在这里看到过类似的问题: Having one button in ng-repeat change color when clicked, not all using Angularjs

他们在哪里使用 ng-class 添加一个类。但对我来说问题是我需要“播放”类来播放音频,而“暂停”类来暂停音频。单击时我不能只添加一个类。

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    您可以改为为每个 r 对象添加一个属性:

    <tr ng-repeat="r in results">
       <i ng-show="r.playButton" ng-click="playedPreview(r,false)" class="material-icons small play" style="cursor:pointer;">play_circle_outline</i>    
       <i ng-show="!r.playButton" ng-click="playedPreview(r,true)" class="material-icons small pause" style="cursor:pointer;">pause_circle_outline</i> 
    </tr>
    

    在控制器中

    $scope.playedPreview = function(obj, state) {
        // reset other objects
        $scope.results.forEach(function(item){
               // perhaps use an if(obj !== item) here
               item.playButton = false;
        });
        obj.playButton = state;
        // use to determine what to play perhaps?
        $scope.activeItem = state ? obj : null;
    
    }
    

    【讨论】:

      【解决方案2】:

      您可以在控制器中使用一个数组来记住每个按钮在点击时切换的当前状态:

      $scope.btnStates = [];
      
      <tr ng-repeat="r in results">
          <i ng-click="playedPreview(true); btnStates[$index]= !buttonStates[$index];" 
             ng-class="buttonStates[$index] ? 'play' : 'pause'" 
             class="material-icons small">
             {{btnStates[$index]? 'play_circle_outline' : 'pause_circle_outline' }}
          </i>   
      </tr>
      

      【讨论】:

        猜你喜欢
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        相关资源
        最近更新 更多