angular module.run ReferenceError: $location is not defined

眉间皱痕 提交于 2019-12-10 02:31:20

问题


I want to AngularJS Change Path Without Reloading, look http://joelsaupe.com/programming/angularjs-change-path-without-reloading/

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

In controller:

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

If invoke changeURL, it will occur error:ReferenceError: $location is not defined

Can somebody help me? Thanks!


回答1:


$location is not injected in the controller, so just change

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

to

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



回答2:


I was getting the same error and I deleted the $rootScope from the definitions. After that it worked. No idea why.

Not working

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

Working

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


来源:https://stackoverflow.com/questions/30013618/angular-module-run-referenceerror-location-is-not-defined

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