admin管理员组

文章数量:1391960

I have links to audio files. With ngRepeat I fill them to In rendered HTML I gets right code, but it doesn't executes.

HTML exaample

    <select ng-model="selectedAudioFile" class="audio-dropdown">
        <option ng-repeat="audioFile in audioFiles" value="{{audioFile.url}}">{{ audioFile.url}}</option>
    </select>

     <audio id="audioNg2">
        <source src="{{selectedAudioFile}}"></source>
     </audio>

     <button ng-click="playNg2()">Play NG2</button>

Detailed on JSFiddle /

First two buttons is working and the last one with angular-repeat and doest'n play sounds. Do you have any ieda why?

I have links to audio files. With ngRepeat I fill them to In rendered HTML I gets right code, but it doesn't executes.

HTML exaample

    <select ng-model="selectedAudioFile" class="audio-dropdown">
        <option ng-repeat="audioFile in audioFiles" value="{{audioFile.url}}">{{ audioFile.url}}</option>
    </select>

     <audio id="audioNg2">
        <source src="{{selectedAudioFile}}"></source>
     </audio>

     <button ng-click="playNg2()">Play NG2</button>

Detailed on JSFiddle http://jsfiddle/paka/LqkwT/

First two buttons is working and the last one with angular-repeat and doest'n play sounds. Do you have any ieda why?

Share Improve this question asked Jun 13, 2013 at 11:29 pakapaka 1,64122 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You need to call .load() if you change the src on and <audio/> element.

$scope.playNg2 = function () {
    var audio = document.getElementById("audioNg2");
    audio.load();
    audio.play();
};

With that being said, you are better off creating a directive since dom manipulation inside of a controller is against angular's ideals.

Some other notes

use ng-options instead of ng-repeat when dealing with select lists.

<select ng-model="selectedAudioFile" class="audio-dropdown" ng-options="audio.url as audio.url for audio in audioFiles">
</select>

Place your methods on your scope instead of having them in the global scope.

Simply on ng-change in select element, execute a function that contains:

var audio = new Audio("audio.src || audio.url");
audio.play();

where audio.src or aurio.url is a reference to the location of the file locally or at a URL address. It is the value of the ng-model of the select element.

本文标签: javascriptAngularJS Could not play audio with source from ltselectgtStack Overflow