我想在 Angular 的 Controller 中使用 HTML5 音频元素属性(播放/停止/暂停/...)。但是我有多个由 foreach 循环生成的音频元素,因此通过 ID 选择不是一个选项(除非我根据 foreach 的索引给出 id,这似乎不是正确的方法)。
我的缩写 html:
<div ng-controller="LoopController">
<a ng-click="playLoop()">Play</a>
<audio id="music" controls loop>
<source src="songs/music1.mp3" type="audio/mpeg">
</audio>
</div>
<div ng-controller="LoopController">
<a ng-click="playLoop()">Play</a>
<audio id="music" controls loop>
<source src="songs/music2.mp3" type="audio/mpeg">
</audio>
</div>
Angular Controller :
gloopsApp.controller('LoopController', ['$scope', function($scope) {
var music = document.getElementById('music');
//here I want to target the audio element that is in this controller
$scope.playLoop = function() {
if (music.paused) {
music.play();
} else {
music.pause();
}
};
}]);
最佳答案
您可以使用$event
获取被点击的元素并找到下一个元素。
此外,不能有多个 dom 元素具有相同的 id
,因此请使用 class
。
以下内容尚未测试,但应该可以工作:
<div ng-controller="LoopController">
<a ng-click="playLoop(event)">
Play
</a>
<audio class="music" controls loop>
<source src="songs/music1.mp3" type="audio/mpeg">
</audio>
</div>
<div ng-controller="LoopController">
<a ng-click="playLoop($event)">
Play
</a>
<audio class="music" controls loop>
<source src="songs/music2.mp3" type="audio/mpeg">
</audio>
</div>
你的js:
gloopsApp.controller('LoopController', ['$scope', function($scope) {
//here I want to target the audio element that is in this controller
$scope.playLoop = function($event) {
var music = angular.element($event.target).next('.music');//or $event.currentTarget
if (music.paused) {
music.play();
}
else {
music.pause();
}
//consider refactoring to
//music.paused ? music.play() : music.pause();
};
}]);
此外,我真的不明白为什么你希望每个 div 有自己的 Controller (尽管从技术上来说这样做是可以的),简单地将 Controller 分配给父元素应该可以正常工作并且会更好假设您有很多音乐元素(只有 1 个范围实例而不是 N 个实例),性能会有所不同。
关于javascript - 如何在 Angular 中使用 Controller 定位 html 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241380/