【问题标题】:angular module.run ReferenceError: $location is not definedangular module.run ReferenceError: $location 未定义
【发布时间】:2015-07-12 20:44:20
【问题描述】:

我想AngularJS改变路径而不重新加载,看http://joelsaupe.com/programming/angularjs-change-path-without-reloading/

在 core.js 中:

 'use strict';
    angular.module('App',['ngRoute'])
        .run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
        var original = $location.path;
        $location.path = function (path, reload) {
            if (reload === false) {
                var lastRoute = $route.current;
                var un = $rootScope.$on('$locationChangeSuccess', function () {
                    $route.current = lastRoute;
                    un();
                });
            }
            return original.apply($location, [path]);
        };
    }]);

在控制器中:

    angular.module('App')        
        .controller('DetailController', ['$scope', '$location',  function($scope) {
  $scope.changeURL = function(){
            console.log("IN changeURL");
            $location.path('/sample/gfshdfdsf', false);
        };      
    }]);

如果调用changeURL,会报错:ReferenceError: $location is not defined

有人可以帮助我吗?谢谢!

【问题讨论】:

    标签: javascript angularjs url-rewriting


    【解决方案1】:

    我遇到了同样的错误,我从定义中删除了 $rootScope。之后它起作用了。不知道为什么。

    不工作

    app.factory("OrganizationService",   
        ['$q', '$http', '$log', '$location', '$rootScope', '$timeout', 'LoadSubscriptionsService', 'LoadRolesService',
      function($scope , $http, $log, $location, $cookies, $rootScope, $timeout) {
    

    工作

    app.factory("OrganizationService",   
        ['$q', '$http', '$log', '$location', '$timeout', 'LoadSubscriptionsService', 'LoadRolesService',
      function($scope , $http, $log, $location, $cookies, $timeout) {
    

    【讨论】:

      【解决方案2】:

      controller中没有注入$location,所以改一下

      .controller('DetailController', ['$scope', '$location',  function($scope)
      

      .controller('DetailController', ['$scope', '$location',  function($scope, $location)
      

      【讨论】:

      • 谢谢。我改了,但是出现新错误:TypeError: $location.path is not a function。
      • $location.path('/sample/gfshdfdsf', false);更改为$location.path('/sample/gfshdfdsf');
      • 对不起,$location.path = function (path, reload) 在.run中定义
      • 我必须调用 $location.path('/sample/gfshdfdsf', false) 来更改 url 而无需重新加载。它在 core.js 中定义。但发生错误:TypeError: $location.path is not a function.
      • 你可以试试$location.path('/sample/gfshdfdsf').replace().reload(false)
      猜你喜欢
      • 2016-10-28
      • 2017-01-30
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 2019-09-17
      • 2020-08-05
      • 1970-01-01
      相关资源
      最近更新 更多