2

I don't quite follow how to inject external constructors, I have this constructor:

function myAudio(url){
    var song = new Audio();
    song.crossOrigin = "anonymous";
    song.src = url;
    var source  = context.createMediaElementSource(song);
    source.connect(context.destination);

    this.play = function(){
        source.mediaElement.play();
    } 

}

outside, just with Javascript it works ok. I can create objects using var myVar = new myAudio("some_url")

I want to use that constructor inside an AngularJS controller but I just can't figure out how to do it.

I tried declaring it in the controller without success

app.controller("myAppCtrl", myMainFunction);
myMainFunction.$inject = ["$interval", "myAudio"];
function myMainFunction($interval, myAudio) {
   scope = this;
   //my controller stuff
}

Tried to make it return an object but I didn't find the correct way to do it.

I don't know what I am missing...

GG.
  • 21,083
  • 14
  • 84
  • 130
distante
  • 6,438
  • 6
  • 48
  • 90

3 Answers3

3

something like that

app.factory('MyAudio', function() {
    function MyAudio(url){
        var song = new Audio();
        song.crossOrigin = "anonymous";
        song.src = url;

        this.source = context.createMediaElementSource(song);
        this.source.connect(context.destination);
    }

    MyAudio.prototype.play = function(){
        this.source.mediaElement.play();
    };

    return MyAudio;
});

app.controller("myAppCtrl", myMainFunction);
myMainFunction.$inject = ["$interval", "MyAudio"];
function myMainFunction($interval, MyAudio) {
    this.myAudio = new MyAudio('/some/url.mp3');
    this.myAudio.play();
    // controller stuff
}
finico
  • 711
  • 7
  • 12
  • Thanks it worked, I just need to be sure that I delete the object every time I need to change the URL – distante Apr 17 '16 at 10:30
0

Register your class as a service like you have registered your controller.

app.service("myAudio", myAudio);

A good sum up about services and injection: https://stackoverflow.com/a/17944367/652669

Community
  • 1
  • 1
GG.
  • 21,083
  • 14
  • 84
  • 130
0

A service is a singleton created by angular using a constructor definition (similar to myAudio). In order to inject the singleton service, you need to tell angular to instantiate it by using below definition:

app.service("myAudio", myAudio);

function myAudio(url){
  var song = new Audio();
  song.crossOrigin = "anonymous";
  song.src = url;
  var source  = context.createMediaElementSource(song);
  source.connect(context.destination);

  this.play = function(){
      source.mediaElement.play();
  } 

}

Then you can inject it in your controller or other services. Refer https://docs.angularjs.org/guide/services for more details

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67