我正在 angularjs 中做项目,我的要求是需要使用 $rootScope 将值从一个不同的应用程序模块控制器传递到另一个应用程序模块服务
Here my part of code
登录模块及控制器
var loginApp = angular.module('loginApp', [ 'ngCookies' ]);
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
$rootScope.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
});
这是我的 app.js 文件
我将登录模块注入到另一个模块中
var smartCities = angular.module('smartCities', [ 'ngRoute', 'ngAnimate',
'ui.bootstrap', 'ngTouch', 'ui.grid.exporter', 'ui.grid',
'ui.grid.selection', 'ui.grid.autoResize', 'ngCookies', 'loginApp' ]);
下面我在这里访问loggedInuser
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log($rootScope.loggedInUser);
$location.path(next.$$route.originalPath);
});
});
但在控制台中我收到类似的消息
undifined
请告诉我哪里做错了
您可以使用本地存储或会话存储来实现此目的。
登录控制器:
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
localStorage.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
登录用户:
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(localStorage.loggedInUser);
$location.path(next.$$route.originalPath);
});
这是文档链接:https://docs.angularjs.org/api/ng/type/angular.Module#value
//this is one module
var myUtilModule = angular.module("myUtilModule", []);
// this is value to be shared among modules, it can be any value
myUtilModule.value ("myValue" , "12345");
//this is another module
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
// myValue of first module is available here
}
myOtherModule.factory("myFactory", function(myValue) {
return "a value: " + myValue;
});
希望有帮助!