4

我正在查看 angularjs 示例,我发现了这个示例:

// 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;
});

我不想使用魔术字符串静态资源,例如https://api.mongolab.com/api/1/databases/angularjs/collections/projects/:id,而是希望在服务器上定义它,然后传递到模块中。我的问题是,你如何参数化模块,即如何从外部将 javascript 变量传递到模块中?

4

1 回答 1

0

仅当您希望为应用程序范围的配置公开 API 时才应使用 Provider 配方,该 API 必须在应用程序启动之前进行。这通常只对可重用服务感兴趣,这些服务的行为可能需要在应用程序之间略有不同。

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;
});

然后你可以配置它

app.config(["projectProvider", function(projectProvider){
    projectProvider.resourceUrl('https://api.mongolab.com/api/1/databases' +
        '/angularjs/collections/projects/:id')
}]);
于 2015-06-11T15:22:21.077 回答