I have a controller that shows a page navigation menu. The menu has an array of items, and each item has a caption and a link. I also set a flag on each item that indicates whether the related page is currently shown:
module.controller('MenuContr', [
/******/ '$scope', '$location',
function ($scope, $location) {
$scope.items = [
{text: 'page 0',
href: '#/page-0',
current: $location.path() === '/page-0'},
{text: 'page 1',
href: '#/page-1',
current: $location.path() === '/page-1'}
];
in my template:
<ul class="menu" ng-controller="MenuContr" ng-cloak>
<li ng-repeat="item in items" ng-switch on="item.current">
<span class="current" ng-switch-when="true">{{item.text}}</span>
<a ng-switch-default ng-href="{{item.href}}">{{item.text}}</a>
</li>
</ul>
I need to be able to update the menu when the location changes, how is it done? Is there an event that I can subscribe to?
EDIT: this controller is used in addition to the controllers that are defined in my routes, and the above template is placed above the element containing ng-view
directive.
Window location. The replace() method replaces the current document with a new one.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
Window Location Href The window.location.href property returns the URL of the current page.
to answer my own question, in my MenuContr
:
$scope.$on('$routeChangeSuccess', function () {
var items = $scope.items;
var path = $location.path();
for (var i = 0; i < items.length; i++) {
var item = items[i];
var href = item['href'];
item['current'] = !!href && href.substring(1) === path;
}
});
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