How to pass parameter to module in angularjs

I am looking through angularjs examples, I found this example:

// This is a module for cloud persistance in mongolab - https://mongolab.com angular.module('mongolab', ['ngResource']). factory('Project', function($resource) { var Project = $resource('https://api.mongolab.com/api/1/databases' + '/angularjs/collections/projects/:id', { apiKey: '4f847ad3e4b08a2eed5f3b54' }, { update: { method: 'PUT' } } ); Project.prototype.update = function(cb) { return Project.update({id: this._id.$oid}, angular.extend({}, this, {_id:undefined}), cb); }; Project.prototype.destroy = function(cb) { return Project.remove({id: this._id.$oid}, cb); }; return Project; }); 

I do not want to use a static magic string resource such as https://api.mongolab.com/api/1/databases/angularjs/collections/projects/:id , instead I would like it to be defined on the server, and then transferred to the module. My question is: how do you parameterize the module, i.e. How do you pass a javascript variable to a module from outside?

+4
source share
1 answer

You should only use the provider recipe when you want to open the API for the entire application configuration that must be completed before the application starts. This is usually only interesting for reusable services, the behavior of which may vary slightly between applications.

 var app = angular.module('mongolab', ['ngResource']) app.provider('project', function projectProvider(){ var resourceUrl = false; this.resourceUrl = function(url){ this.resourceUrl = url; } this.$get = [function project(){ return new Project(resourceUrl); }]; }); function Project(resourceUrl) { var Project = $resource(resourceUrl, { apiKey: '4f847ad3e4b08a2eed5f3b54' }, { update: { method: 'PUT' } } ); Project.prototype.update = function(cb) { return Project.update({id: this._id.$oid}, angular.extend({}, this, {_id:undefined}), cb); }; Project.prototype.destroy = function(cb) { return Project.remove({id: this._id.$oid}, cb); }; return Project; }); 

Then you can configure it with

 app.config(["projectProvider", function(projectProvider){ projectProvider.resourceUrl('https://api.mongolab.com/api/1/databases' + '/angularjs/collections/projects/:id') }]); 
0
source

Source: https://habr.com/ru/post/1479168/


All Articles