在AngularJS中为子模块配置restmod

时间:2015-01-02 17:35:31

标签: angularjs angularjs-module

所以我将主模块app定义为

app = angular.module("app", ['app.social_accounts', 'restmod'])

配置了restmod模块:

app.config(function(restmodProvider) {
    restmodProvider.rebase({
    $config: {
        primaryKey: "id",
        style: "ams",
        urlPrefix: "/app/"
    }
  });
});

并且按预期工作:请求已发送到http://localhost:8000/app/...

现在我想通过

在子模块restmod中使用app.social_accounts
app = angular.module("app.social_accounts", ['restmod'])

app.config(function(restmodProvider) {
    restmodProvider.rebase({
    $config: {
        primaryKey: "id",
        style: "ams",
        urlPrefix: "https://graph.facebook.com/"
    }
  });
});
app.factory("Album", ["restmod", function(restmod){
    Album = restmod.model("/me/albums/")
    return {
        "get": function(){Album.$search()}
    }
}])

即我想在子模块url中使用绝对app.social_accounts

但是当我将Album(在app.social_accounts下注册)注入controller下的DashboardCtrl app时,请求已发送至http://localhost:8000/app/me/albums/

所以我想知道这里发生了什么,以及如何在url下为restmod单独app.social_accounts

1 个答案:

答案 0 :(得分:2)

使用restmodProvider定义的任何配置对于restmod都是全局的,无论其使用的模块如何。因此,在上面的示例中,urlPrefix模块中定义的app.social_accounts是被app模块中的配置覆盖。

为了实现您期望的行为,您可以基于每个模型覆盖配置:

angular.module('app.social_accounts', ['restmod'])

  .factory('Album', function(restmod) {
     var Album = restmod.model('/me/albums')
       .mix({
         $config: {
           urlPrefix: 'https://graph.facebook.com/'
         }
       });
   });

如果您需要在模块中的多个模型中进行配置,可以使用mixin来保持干燥:

.factory('restmodConfigSocial', function(restmod) {
  return restmod.mixin({
    $config: {
      urlPrefix: 'https://graph.facebook.com/'
    }
  });
})

.factory('Album', function(restmod) {
  var Album = restmod.model('/me/albums').mix('restmodConfigSocial');
});