4

I'm looking through angularjs examples, I've 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 don't want using magic string static resource such as https://api.mongolab.com/api/1/databases/angularjs/collections/projects/:id, instead I would like to have it defined on server and later passed into the module. My question is, how do you parametrize module, i.e. how do you pass a javascript variable into the module from outside?

Lu4
  • 14,873
  • 15
  • 79
  • 132
  • Maybe this one could inspire you doing it http://stackoverflow.com/questions/16339595/angular-js-configuration-for-different-enviroments/16340438#16340438 – kfis May 04 '13 at 20:54
  • I'll try defining my config module in View file, thanks – Lu4 May 04 '13 at 21:14
  • I don't know if I understand correctly what you are looking for, but I think you need to use provider instead of factory https://docs.angularjs.org/guide/providers#provider-recipe – TlmaK0 Jun 11 '15 at 14:47

1 Answers1

0

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to 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 config it with

app.config(["projectProvider", function(projectProvider){
    projectProvider.resourceUrl('https://api.mongolab.com/api/1/databases' +
        '/angularjs/collections/projects/:id')
}]);
TlmaK0
  • 3,578
  • 2
  • 31
  • 51