molunoluda molunoluda - 2 months ago 15
AngularJS Question

UI-Router parent view not working in angular

I'm creating an application and in the dashboard I have the header and the sidebar that will be in every single page of the dashboard, and for that reason I created partial files for them.

The problem is that if I access

/dashboard/users
I get the same thing that is in the
/dashboard
, I was wondering how to keep the header and sidebar but change the main content to the
/views/dashboard/users.html
file?


I created the states like this:

.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');

$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.state('dashboard', {
url: '/dashboard',
views: {
'': {
templateUrl: 'views/dashboard.html'
},
'header@dashboard': {
templateUrl: 'views/dashboard/partials/header.html'
},
'sidebar@dashboard': {
templateUrl: 'views/dashboard/partials/sidebar.html'
}
},
controller: 'DashboardCtrl',
controllerAs: 'dashboard'
})
.state('dashboard.users', {
url: '/users',
views: {
'': {
templateUrl: 'views/dashboard/users.html'
}
},
controller: 'DashboardUsersCtrl',
controllerAs: 'dashboard/users'
});
});


/main.html


<p>main</p>


/index.html


<body ng-app="freelancerApp">
<div ui-view></div>
</body>


/views/dashboard.html


<div ui-view="header"></div>
<p>dashboard</p>
<div ui-view="sidebar"></div>


/views/dashboard/users.html


<div ui-view="header"></div>
<p>users</p>
<div ui-view="sidebar"></div>


/views/dashboard/partials/header.html


</p>header</p>


/views/dashboard/partials/sidebar.html


<p>sidebar</p>

Answer

I would say, that your parent template, is just missing place for a child (unnamed view target)

//views/dashboard.html
<div ui-view="header"></div>
<p>dashboard</p>
<div ui-view="sidebar"></div>

should be

//views/dashboard.html
<div ui-view="header"></div>
<div ui-view="">
  // we can keep it or remove the content
  <p>dashboard</p> // just visible in parent
</div>
<div ui-view="sidebar"></div>

Now, we have a target <div ui-view=""></div> for an unnamed child view, defined as views :{ '': {...}} in a .state('dashboard.users'...

Comments