M. Bhamre M. Bhamre - 8 months ago 40
AngularJS Question

Is it possible to reinstantiate Services And Factories without refreshing page in angular?

I need to change domainUrl dynamically in services.For example I need to get user list by selecting specific organization, and url should change accordingly.

app.factory('User', ['$resource', function($resource) {
var baseUrl = 'http://foo.com/users'
return $resource(baseUrl + '.json');

I need baseUrl "http://example.com" on selecting another organization. I don't want to refresh page.


Try this:

app.factory('User', ['$resource', function($resource) {
    return function(baseUrl) {
        baseUrl = baseUrl || 'http://foo.com/users';
        return $resource(baseUrl + '.json');

Now the User factory will return a function which you can call with a baseUrl to instantiate a resource.

app.controller('exampleController', function(User) {
    var example1 = User('http://www.example1.com');
    var example2 = User('http://www.example2.com');