Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect location change

Tags:

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.

like image 760
akonsu Avatar asked Nov 17 '12 00:11

akonsu


People also ask

What does Window location replace do?

Window location. The replace() method replaces the current document with a new one.

What does Window addEventListener do?

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.

What is window location href?

Window Location Href The window.location.href property returns the URL of the current page.


1 Answers

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;
            }
        });
like image 130
akonsu Avatar answered Oct 06 '22 08:10

akonsu