¿Cómo observar un cambio de ruta en AngularJS?


Respuestas:


330

Nota : Esta es una respuesta adecuada para una versión heredada de AngularJS. Vea esta pregunta para versiones actualizadas.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

Los siguientes eventos también están disponibles (sus funciones de devolución de llamada toman diferentes argumentos):

  • $ routeChangeSuccess
  • $ routeChangeError
  • $ routeUpdate: si la propiedad reloadOnSearch se ha establecido en falso

Ver los $ route docs.

Hay otros dos eventos indocumentados :

  • $ locationChangeStart
  • $ locationChangeSuccess

Consulte ¿Cuál es la diferencia entre $ locationChangeSuccess y $ locationChangeStart?


38
También debe inyectar "$ route" en algún lugar o estos eventos nunca se activarán.
Kevin Beal

19
$locationChangeStarty $locationChangeSuccessahora están documentados! docs.angularjs.org/api/ng.$location
JP ten Berge

2
@KevinBeal gracias, gracias, gracias . Me estaba volviendo loco tratando de averiguar por qué estos eventos no se dispararon.
Dan F

44
Solo una nota para todos los que usan $ state, en lugar de $ route. En ese caso, debe inyectar $ state y usar $ stateChangeStart.
tomazahlin

77
Es $rootScope.$on("$routeChangeStart", function (event, next, current) {ahora
abbaf33f

28

Si no desea colocar el reloj dentro de un controlador específico, puede agregar el reloj para toda la aplicación en la aplicación Angular run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});

1
Me encanta cuando encuentro una respuesta como esta y encuentro algo que no sabía como .run () aunque no es donde necesitaba el detector de eventos en mi caso de uso particular, es muy útil para mí. Gracias zanon
Paul J

Estoy aprendiendo angular. así que necesito saber qué tipo de información podemos obtener del evento, el próximo argumento actual.
Monojit Sarkar

11
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});

2
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

-1

Esto es para el principiante total ... como yo:

HTML:

  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});

Espero que esto ayude a un principiante como yo. Aquí está la muestra de trabajo completa:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>
</head>
<body>
  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>
  <script>
//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});
  </script>
</body>
</html>

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.