为什么不会$ location.path触发$ routeChangeStart控制器? [英] Why won't $location.path trigger a $routeChangeStart in the controller?

查看:306
本文介绍了为什么不会$ location.path触发$ routeChangeStart控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试有:

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

我的控制器是:

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?

推荐答案

您需要注入$路​​线,因为$ routeChangeStart是$路由触发的事件。

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

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

不知道你的使用情况,如果你只需要检测的URL更改,您可以侦听$ locationChangeStart代替。 $ locationChangeStart是从$位置发射,这样你就不会需要注入任何新的依赖关系。

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.

这篇关于为什么不会$ location.path触发$ routeChangeStart控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆