Why won't $location.path trigger a $routeChangeStart in the controller?

巧了我就是萌 提交于 2019-12-24 11:33:57

问题


My test has:

it("should clear the search field when the URL changes", function() {
  createController();
  $scope.init();
  $scope.searchTerm = 'some term';

  $location.path('/source');
  $rootScope.$apply();

  expect($scope.searchTerm).toBe('');
});

My controller is:

angularMoonApp.controller('SearchController', ['$scope', '$location', function ($scope, $location) {
  $scope.init = function() {
  $scope.$on('$routeChangeStart', function(next, current) {
    $scope.searchTerm = '';
  });

  }

  $scope.init();
}]);

Seems simple enough! So why won't that trigger when I Change the location in the test?


回答1:


You need to inject $route, since $routeChangeStart is an event triggered by $route.

angularMoonApp.controller('SearchController', ['$scope', '$location', '$route', function ($scope, $location, $route) {

Without knowing your use case, if you just need to detect that the url changed, you can listen for $locationChangeStart instead. $locationChangeStart is fired from $location, so you would not need to inject any new dependencies.



来源:https://stackoverflow.com/questions/23525246/why-wont-location-path-trigger-a-routechangestart-in-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!