我有一个带有此代码的脚本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:无法设置未定义的属性'edition'
感谢。
答案 0 :(得分:2)
Array中的字符串元素必须与函数本身注入的依赖项(作为参数)匹配:
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) {
...
});
答案 1 :(得分:0)
以正确的顺序添加所有依赖项,因为您错过了一些(如$state
)
myApp.controller('ImageController',
['$rootScope', '$scope', '$window', '$location', '$document', '$state',
function ($rootScope, $scope, $window, $location, $document, $state) {
// code
});
答案 2 :(得分:0)
问题在于这一行。你的数组提到了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) {