javascriptangularjsaudioangularjs-directiveangularjs-ng-repeat

Can I use Angular variables as the source of an audio tag?


I am trying to do the following:

<div ng-repeat="audio in event.audios">
    <audio ng-src="/data/media/{{audio}}" controls></audio>
</div>

But when I load the view, the {{audio}} variable is not parsed but hardcoded into the source as is. However, if for example, I place that same variable outside of the audio tag it renders the name of the audio file correctly. I've tried using both src and ng-src to no avail.

Is there a way to get the variable to work within an audio tag?

Thanks in advance.


Solution

  • Ok, thanks to theJoeBiz's input and some thinking around I solved this by making a directive, here is the code:

    app.directive('audios', function($sce) {
      return {
        restrict: 'A',
        scope: { code:'=' },
        replace: true,
        template: '<audio ng-src="{{url}}" controls></audio>',
        link: function (scope) {
            scope.$watch('code', function (newVal, oldVal) {
               if (newVal !== undefined) {
                   scope.url = $sce.trustAsResourceUrl("/data/media/" + newVal);
               }
            });
        }
      };
    });
    

    Then on the template I used it like so:

    <div ng-repeat="audio in event.audios">
        <div audios code="audio"></div>
    </div>
    

    It is all working fine now.