Skip to content Skip to sidebar Skip to footer

Use External Class In AngularJs Controller

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.s

Solution 1:

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
}

Solution 2:

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


Solution 3:

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


Post a Comment for "Use External Class In AngularJs Controller"