I am trying to build a pretty complex app. This app involves many different state, config and run blocks in their own respective modules. I figured that one good way to tie these modules together would be to inject them into a main app
module which holds all the injected modules. In this specific case, subapp
is the injected, child module.
I am finding out though, that subapp
's run and config blocks don't run as if they were their parents, let me demonstrate that below:
HTML
<html ng-app="app">
<body>
<a href="#/thestate">Head to the state!</a>
<ui-view></ui-view>
</body>
</html>
JS
angular.module('app', ['ui.router', 'subapp']);
angular.module('subapp', ['ui.router'])
.run(function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (toState.name === "theState") {
event.preventDefault();
$state.go('theState.substate', {
param: 1
});
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('theState', {
url: '/thestate',
template: '<div>this is the main state</div>' +
'<a href="#/thestate/12">Go to state.substate</a>' +
'<ui-view></ui-view>'
})
.state('theState.substate', {
url: '/:param',
template: '<div>{{id}}</div>',
controller: function($scope, $stateParams) {
$scope.id = $stateParams.param;
}
});
$urlRouterProvider.otherwise('/');
});
Essentially, I'm trying to get Angular to run the .run
and .config
functions of subapp
but use <html ng-app="app">
in the instantiation.
Upon trying to navigate to <a href="#/thestate">
, nothing happens. It does work, obviously, if I replace <html ng-app="app>
with <html ng-app="subapp">
but this wouldn't allow me to do something like, angular.module('app', ['ui.router', 'subapp', 'subapp2' ...]);
So, my question is, why doesn't this work—(i.e., maybe .run
is only run once, and only from the module instantiated in the html), and what is the best way to approach something modular like this?
Thanks a bunch!
EDIT**
Plnkr: http://plnkr.co/edit/UCWc2cByHHjNgqAE8P7L?p=preview
There is updated plunker
The only issue with .run()
of the main module is missing []
.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
The original code snippet:
.run('$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
})
is not doing what angular would expect
.run(['param1', 'param2', ... , function(param1, param2, ...) {}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With