plong0 plong0 - 2 days ago 6
AngularJS Question

Is it possible to replace/overwrite a ui-router state definition? (default state being "customized" by another module)

Is it possible to simply replace a state definition with a new one?

The use case I have is that one module defines the state, and I'd like to be able to replace that state definition from a different module. Basically the initial definition is a "default" definition, and I'd like to have the possibility to customize the state from a different module.

I realize that doing this at config time could result in a race condition on which module defines it first. I looked into the possibility of doing it at run-time, but couldn't get it working.

I can accomplish what I want by creating entirely new states, but I would like to use the same URL from the original state.

Edit:

To further clarify what I am trying to accomplish...
Please consider the following code:

angular.module('module1', ['ui.router'])
.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('root', {
url: '',
abstract: true,
template: '<div class="layout sub" ui-view="sub"></div>'
})
.state('root.sub1', {
url: '/sub1',
views: {
'sub@root': {
template: '<p>Default sub state 1</p>'
}
}
});
}]);

angular.module('module2', ['ui.router'])
.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('root.sub1', {
url: '/sub2',
views: {
'sub@root': {
template: '<p>Customized sub state 1</p>'
}
}
});
}]);


Which of course gives "Error: State 'root.sub1'' is already defined"

Answer

Ok, so as I was putting together a plnkr demo of what I tried next, I found that it actually works if you use $state.get and update it.

angular.module('module2', ['ui.router'])
.run(['$state', function($state){
  var state = $state.get('root.sub1');
  if(state && state.views && state.views['sub@root']){
    state.views['sub@root'].template = '<p>Customized sub state 1</p>';
  }
}]);

Plnkr: http://plnkr.co/edit/xLdCgjeM33z2Hf5CHfZR

Edit:

I figured out that it wasn't working in my app because I didn't define the view I wanted to override in the original state.

Example (doesn't work):

angular.module('module1', ['ui.router'])
.config(['$stateProvider', function($stateProvider){
    $stateProvider
        .state('root', {
            url: '',
            abstract: true,
            template: '<div class="layout sub" ui-view="sub"></div>'
        })
        .state('root.sub1', {
            url: '/sub1',
            views: {
            }
        });
}]);

angular.module('module2', ['ui.router'])
.run(['$state', function($state){
    var state = $state.get('root.sub1');
    if(state && state.views){
        state.views['sub@root'] = { template: '<p>Customized sub state 1</p>' };
    }
}]);
Comments