Angularjs 为什么赢了';t$location.path是否在控制器中触发$routeChangeStart?
我的测试有:Angularjs 为什么赢了';t$location.path是否在控制器中触发$routeChangeStart?,angularjs,unit-testing,karma-jasmine,Angularjs,Unit Testing,Karma Jasmine,我的测试有: 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(''); }); 我的
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();
}]);
看起来很简单!那么,为什么在我更改测试中的位置时不会触发该事件呢?您需要注入$route,因为$routeChangeStart是由$route触发的事件
angularMoonApp.controller('SearchController', ['$scope', '$location', '$route', function ($scope, $location, $route) {
在不了解您的用例的情况下,如果您只需要检测url的更改,您可以监听$locationChangeStart$locationChangeStart是从$location启动的,因此您不需要注入任何新的依赖项。这可能会有帮助: