I have a parent view that contains a navbar, and inside of that view I have a <div ui-view>
element which renders whatever child view I'm on.
I want to conditionally show/hide the navbar within the parent view, based on the route of the child view. Right now, I have this:
<nav ng-show="!vm.hideNavbar">
The first time my app is loaded, vm.hideNavbar
is set to true and this works as expected.
After vm.hideNavbar
is changed to false, the bound value is not updated. It is still true
.
Every controller in my app extends this BaseController
:
export class BaseController {
public hideNavbar: boolean;
constructor(public $scope: IBaseScope, private $state: ng.ui.IStateService) {
if ($state.current.url === '/login') {
this.hideNavbar = true;
} else {
this.hideNavbar = false;
}
$scope.vm = this;
}
}
So, everytime a new controller is loaded, it calls the constructor for BaseController
and conditionally sets $scope.vm.hideNavbar
. If I immediately run $scope.$apply()
at the end of this constructor, angular throws errors saying the digest cycle is already being ran.
So, the digest cycle is being ran, but the value in my view is not being updated. My only thought is that I have instantiated more than one copy of the BaseController
since my initial controller and the controller I navigated to both extend this controller. So, now, my bound value of vm.hideNavbar
is still looking at the old controller.
Am I on the right track with this? How can I solve this issue?
In this case, I would suggest to go with
view inheritance
(notcontroller
, notstate
). Check more details here:There is a working example
What we would need is a
'root'
state. It will be the super parent of any otherstate
(states family). This could be the state definition:even some other state hierarchy will start with that
'root'
state:We can see many
controllers:...
being defined, and here they are:As mentioned in the snippet comment - there is inheritance, but just on a code level. The passed
$scope
is inherited by view hierarchy.The first controller in the view hierarchy is
RootCtrl
which will in fact be the only, who will assign (create) the shared reference modelrootSetting : {}
And they all derive from this one controller base:
Having that in place, with this root template:
We can see, that here we evaluate the shared reference model
rootSetting
and its propertyhideNavbar
This is the real advantages of
view inheritance
coming withUI-Router
.Check it in action here