akonsu
akonsu

Reputation: 29536

how to detect location change

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.

Upvotes: 20

Views: 17503

Answers (2)

akonsu
akonsu

Reputation: 29536

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;
            }
        });

Upvotes: 21

Sandeep Shabd
Sandeep Shabd

Reputation: 721

Are you coming to same controller on route change ? Is that way you have defined in $routeProvider in AppsModule.config ? You can pass $routeParams to same controller, if you want additional filtering.

You have initialized the object at start of your controller. So, once the link is changed, the same controller will be called and you do not have to do any other thing. Based on route selected, items will get updated.

Upvotes: 0

Related Questions