在AngularJS模块中包装javascript类并注入角度服务的正确方法

前端之家收集整理的这篇文章主要介绍了在AngularJS模块中包装javascript类并注入角度服务的正确方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我正在开发的AngularJS模块中,我有一个Canvas类定义为:

angular.module("myModule",[])
.factory("Canvas",function() {return Canvas;});

var Canvas = function(element,options) {
    this.width = options.width || 300;
    this.height = options.height || 150;
    this.HTMLCanvas = $(element).get(0);
    this.HTMLCanvas.width = canvas.width;
    this.HTMLCanvas.height = canvas.height;
    this.objects = [];
    //Initialize canvas
    this.init();
}
Canvas.prototype.init = function() {/*...*/};
Canvas.prototype.otherMethod = function() {/*...*/};

现在,Canvas类从不在模块内部实例化,而是从AngularJS控制器实例化,如下所示:

angular.module("myApp.controllers",["myModule"])
.controller("MainCtrl",["Canvas",function(Canvas) {
    var canvas = new Canvas("#canvas",{/*options object*/});
    //...
}]);

到目前为止,一切都像一个魅力.
但后来我意识到我需要在我的canvas对象中使用$q服务,因为我不想将它注入我的控制器然后将它传递给Canvas构造函数,我想要修改我的模块,如下所示:

angular.module("myModule",["$q",function(q) {
    var that = this;
    that.q = q;
    return function() {
        Canvas.apply(that,arguments);
    };
}]);

var Canvas = function(element,options) {
    console.log(this.q,element,options);
    this.width = options.width || 300;
    this.height = options.height || 150;
    this.HTMLCanvas = $(element).get(0);
    this.HTMLCanvas.width = canvas.width;
    this.HTMLCanvas.height = canvas.height;
    this.objects = [];
    //Initialize canvas
    this.init();
}
Canvas.prototype.init = function() {/*...*/};
Canvas.prototype.otherMethod = function() {/*...*/};

最初的console.log正确记录了$q服务和Canvas的原始参数,元素和选项,但在调用其init方法时中断了:

TypeError:undefined不是函数

我想这是因为它不再是Canvas的实例,而是匿名函数函数(q){…}.
有关如何使用q属性实例化新Canvas对象并仍然保留类的方法的任何提示

编辑

我稍微修改了我的代码,以便更好地了解我想要实现的目标:

angular.module("myModule",[])
//.factory("Canvas",function() {return Canvas;})
//.factory("Canvas",CanvasFactory])

function CanvasFactory(q) {
    var canvas = this;
    canvas.q = q;
    return function() {
        Canvas.apply(canvas,arguments);
    };
}

var Canvas = function(element,options) {
    console.log(this instanceof Canvas,typeof this.q !== "undefined");
};

如果我取消注释第一个工厂,console.log产生true false,而第二个工厂产生false true.我的目标是实现真,这意味着这实际上是Canvas类的一个实例,并且定义了q属性.非常感谢任何提示.

解决方法

我想到了:

angular.module("myModule",function(q) {
    Canvas.prototype.q = q;
    return Canvas;
}]);

var Canvas = function(element,typeof this.q !== "undefined");
};

此日志:true true.

猜你在找的Angularjs相关文章