我有一个带有以下代码的脚本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";
}
}
});
但是我有这个错误,我也不知道为什么。如何在运行和控制器之间传递全局变量。它用于操作URL而无需重新加载。
TypeError:无法设置未定义的属性“版本”
谢谢。
最佳答案
将所有依赖项以正确的顺序添加到函数中,因为您错过了一些依赖项(例如$state
)
myApp.controller('ImageController',
['$rootScope', '$scope', '$window', '$location', '$document', '$state',
function ($rootScope, $scope, $window, $location, $document, $state) {
// code
});
关于javascript - 运行和 Controller angularjs之间的全局变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30669986/