使用外部类中AngularJs控制器 [英] Use external class in AngularJs controller

查看:122
本文介绍了使用外部类中AngularJs控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太明白如何注入外部的构造,我有这样的构造:

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();
    } 

}

外,只需使用Javascript它工作正常。我可以创建一个使用 VAR myVar的=新myAudio(SOME_URL)对象

我想使用AngularJS控制器内该构造,但我只是无法弄清楚如何做到这一点。

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

推荐答案

这样的事情

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
}

这篇关于使用外部类中AngularJs控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆