【问题标题】:Why won't $location.path trigger a $routeChangeStart in the controller?为什么 $location.path 不会在控制器中触发 $routeChangeStart?
【发布时间】:2014-06-24 20:52:42
【问题描述】:

我的测试有:

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

看起来很简单!那么为什么我在测试中更改位置时不会触发呢?

【问题讨论】:

标签: angularjs unit-testing karma-jasmine


【解决方案1】:

你需要注入$route,因为$routeChangeStart是一个由$route触发的事件。

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

在不了解您的用例的情况下,如果您只需要检测 url 更改,则可以改为侦听 $locationChangeStart。 $locationChangeStart 是从 $location 触发的,因此您不需要注入任何新的依赖项。

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2011-04-17
    • 2012-03-31
    相关资源
    最近更新 更多