在AngularJS模块中包装javascript类并注入角度服务的正确方法
发布时间:2020-12-17 17:31:51 所属栏目:安全 来源:网络整理
导读:在我正在开发的AngularJS模块中,我有一个Canvas类定义为: angular.module("myModule",[]).factory("Canvas",function() {return Canvas;});var Canvas = function(element,options) { this.width = options.width || 300; this.height = options.height ||
在我正在开发的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*/}); //... }]); 到目前为止,一切都像一个魅力. 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){…}. 编辑 我稍微修改了我的代码,以便更好地了解我想要实现的目标: 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |