javascript - 更改 ng-repeat 中的一个按钮(元素)

标签 javascript html angularjs

我有一个根据 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>

在我的 Controller 中:

$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 添加类。但对我来说,问题是我需要“播放”类来播放音频,需要“暂停”类来暂停音频。我不能只在单击时添加一个类。

最佳答案

您可以向每个 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>

在 Controller 中

$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;

}

关于javascript - 更改 ng-repeat 中的一个按钮(元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43333697/

相关文章:

javascript - 将动态创建的 id 传递给 getElementById

html - 如何使用 CSS3 为字体粗细设置动画?

javascript - 在图像上的新选项卡中打开链接,单击 Angular 而不使用弹出窗口拦截器

javascript - 无法在选择框中设置选定值

javascript - 启动时虚拟地球 map 不显示为显示 :none

javascript - 删除子节点,除了首先使用 javascript

python - 目前,在 Django 通知中,每次我发送通知时,它都会以纯文本形式发送电子邮件

javascript - 如何防止按钮出现悬停

javascript - 如何监视函数中调用的属性?

javascript - 咏叹调完成状态?