Correct way of wrapping javascript class in AngularJS module and inject angular services

后端 未结 2 1638
误落风尘
误落风尘 2021-01-03 06:48

Inside an AngularJS module I\'m developing, I have a Canvas class defined as:

angular.module(\"myModule\", [])
.factory(\"Canvas\", function() {         


        
相关标签:
2条回答
  • 2021-01-03 07:00

    I figured it out:

    angular.module("myModule", [])
    .factory("Canvas", ["$q", function(q) {
        Canvas.prototype.q = q;
        return Canvas;
    }]);
    
    var Canvas = function(element, options) {
        console.log(this instanceof Canvas, typeof this.q !== "undefined");
    };
    

    This logs: true true.

    0 讨论(0)
  • 2021-01-03 07:10

    I create Canvas service like this and is work:

    var app = angular.module('myModule', []);
    
    app.factory("Canvas", ["$q", function($q) {
    
        var Canvas = function(element, options) {
            this.q = $q;
    
            this.init();
            console.log(this.q, element, options);
        }
        Canvas.prototype.init = function() {/*...*/};
        Canvas.prototype.otherMethod = function() {/*...*/};
    
        return Canvas;
    }]);
    
    app.controller('MainCtrl', ['$scope', 'Canvas', function($scope, Canvas) {
        console.log( new Canvas().q );  
    }]);
    

    Also you can see this on Pluncer here

    0 讨论(0)
提交回复
热议问题