运行和控制器之间的全局变量

Global variable between run and controller angularjs

本文关键字:全局变量 之间 控制器 运行      更新时间:2023-09-26

我有一个脚本angularjs与以下代码:

var myApp = angular.module('App_example', ['duScroll'])
.run(function($rootScope, $location, $window) {
    var url = $window.location.href;
    if( url.indexOf("section1") != -1 ) {
        $rootScope.edition = "section1";
    } else {
        if(url.indexOf("section2") != -1) {
            $rootScope.edition = "section2";
        } else if(url.indexOf("section3") != -1) {
            $rootScope.edition = "section3";
        } else {
            $rootScope.edition = "section4";
        }
     }
     if(!history || !history.replaceState) {
         return;
     }
     $rootScope.$on('duScrollspy:becameActive', function($event, $element){
         //Automaticly update location
         var hash = $element.prop('hash');
         if (hash) {
             history.replaceState(null, null, hash+'_'+$rootScope.edition);
         }
     });
});

和这个控制器:

myApp.controller('ImageController', ['$scope', '$window', '$location', '$document', '$rootScope', function($scope,$window,$location,$document,$state,$rootScope) {
     var url = $window.location.href;
     if( url.indexOf("section1") == -1 ) {
        $rootScope.edition = "section1";
     } else {
        if(url.indexOf("section2") != -1) {
            $rootScope.edition = "section2";
        } else if(url.indexOf("section3") != -1) {
            $rootScope.edition = "section3";
        } else {
            $rootScope.edition = "section4";
        }
     }
});

但是我有以下错误,我不知道为什么。我如何在运行和控制器之间传递全局变量。

TypeError: Cannot set property 'edition' of undefined

谢谢。

数组中的字符串元素必须匹配注入到函数本身的依赖项(作为参数):

myApp.controller('ImageController', 
['$scope', '$window', '$location', '$document', '$state', '$rootScope', 
function ($scope, $window, $location, $document, $state, $rootScope) { 
    ... 
}]);

那是因为你正在使用"带注释的依赖注入",也就是说,你在将依赖项注入控制器之前显式地用字符串命名它们。这是避免最小化问题的最佳实践,如下所示:angular docs

也就是说,您也可以通过直接传递函数来解决这个问题,而不需要注释依赖关系,像这样:
myApp.controller('ImageController', 
function ($scope, $window, $location, $document, $state, $rootScope) { 
    ... 
});

按正确的顺序添加所有依赖函数,因为您错过了一些(如$state)

myApp.controller('ImageController', 
   ['$rootScope', '$scope', '$window', '$location', '$document', '$state',  
   function ($rootScope, $scope, $window, $location, $document, $state) {
      // code 
   });

问题出在这一行。你的数组提到了5个参数,但是你的函数需要6个参数。您忘记将$state添加到数组中。在您的代码中,它将把$rootScope分配给$state对象,而$rootScope将是未定义的。

myApp.controller('ImageController', ['$scope', '$window', '$location', '$document', '$rootScope', function($scope,$window,$location,$document,$state,$rootScope) {

只需将$state添加到数组中,您的代码就可以正常工作了。

myApp.controller('ImageController', ['$scope', '$window', '$location', '$document', '$state', '$rootScope', function($scope,$window,$location,$document,$state,$rootScope) {