Fire event when route is unchanged angularjs

70 Views Asked by At

I want to perform a reload of a route ONLY when there's not a route change, in other words reload a controller when a button that takes to its route is clicked. In my view in the ng-click directive I call the following method:

this.reload = function() {
  $scope.$on('$routeChangeStart', function(event, next, current) {
    if($route.current == $route.next) {
      $route.reload();
    }
  })
}

The code inside the condition is never triggered because there's not a change in the route. I'm a beginner in angularJS, so any help will be appreciated :)

1

There are 1 best solutions below

0
On

I would handle the two things you mentioned above separately.

  1. On each route change do whatever you want to do.

Register an event listener that listens for routeChangeStart.

$rootScope.$on('$routeChangeStart', function (event, next, prev) {
    //if logic given what you want to do with the next/prev objects
});
  1. If a user clicks a button reload a route.

html

<button ng-click="reload_route()">reload</button>

controller

  app.controller('myCtrl', function($scope, $route){
     $scope.reload_route = function(){
        //once again add if logic in here if needed
        $route.reload();
     }
  })

Also, in your above example the $routeChangeStart function executes a callback and is passed the event, next, and prev objects. You should be using those arguments in your if statements, not $route.current or $route.next.