如何从控制器访问工厂

时间:2016-07-05 12:53:34

标签: angularjs dependency-injection

我有factory这样:

rasm.factory('serviceUrl',[function(){
        function serviceUrl(){
            this.p = location.protocol;
            this.h = getHost();
        }
        serviceUrl.prototype.getServiceUrl = function(){
            return this.p +'//'+ this.h + '/services/'
        }
    }])

我已经以javascript面向对象的方式实现了这个。这是我使用过的资源 https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc#.du8tor7h2

我的问题是,如何从我的控制器访问此 getServiceUrl 功能。这有可能吗?谢谢你们

1 个答案:

答案 0 :(得分:4)

了解Dependency Injection。您首先需要更改该工厂代码:

rasm.factory('serviceUrl',[function(){
    function serviceUrl(){
        this.p = location.protocol;
        this.h = getHost();
    }
    serviceUrl.prototype.getServiceUrl = function(){
        return this.p +'//'+ this.h + '/services/'
    }

    // This line has been added
    return serviceUrl;
}]);

然后在你的控制器中使用它:

myApp.controller('MyCtrl', ['$scope', 'serviceUrl', function($scope, serviceUrl) {

     serviceUrl.getServiceUrl();
}]);

<强>更新

我建议你改变你的工厂代码:

rasm.factory('serviceUrl', [function() {
    var _this = this;

    _this.p = location.protocol;
    _this.h = getHost();

    return {
        getServiceUrl: function() {
            return _this.p +'//'+ _this.h + '/services/'
        }
    }
}]);