我有一个索引页index.html
及其控制器indexController
。我在indexController
的factory
中设置了一些值($ scope.ipAddress),其中ng-view
中的其他控制器使用该值。执行主控制器后执行控制器
加载页面时,应该首先执行indexController
,然后在factory
中设置一个值,然后该值由ng-view
内的其他页面控制器使用。
但我认为其他控制器在indexController
之前首先执行,我得到我设置的值未定义。
这是indexController
与factory
:
angular.module('tollApp')
.controller('indexController', function($scope,$http,$window,userDetailsFactory){
$scope.usernameFromServer={};
$scope.getUserDetails = function(){
$http({
method:'GET',
url:'http://192.168.1.80:4000/getUserDetails'
// url:'http://websitename.com/getUserDetails'
})
.then(function(response){
// console.log(JSON.stringify(response));
userDetailsFactory.setUserDetailsInFactory(response.data);
$scope.usernameFromFactory = userDetailsFactory.getUserDetailsFromFactory().usernameFromSession;
$scope.theIP = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
// $scope.usernameFromServer = userDetailsFactory.getUserDetailsFromFactory().username;
// console.log(JSON.stringify($scope.usernameFromFactory)+"usernameFromFactory");
})
}
$scope.logout = function(request,response){
$http({
method:'GET',
url:'/logout'
})
.then(function(response){
console.log(JSON.stringify(response));
if(response.data=="logout"){
// $window.location.href="http://websitename.comlogin";
$window.location.href="http://192.168.1.80:4000/login";
}
})
}
console.log("indexController");
}).factory('userDetailsFactory',function(){
var user = {};
return {
setUserDetailsInFactory : function(val){
user.useridFromSession = val[0].UserID;
user.usernameFromSession = val[0].UserName;
user.userroleFromSession = val[0].UserRole;
user.clientidFromSession = val[0].ClientID;
user.ipAddress = "http://192.168.1.80:4000/";
// user.ipAddress = "http://websitename.com/";
// console.log("in set "+user.clientidFromSession);
},
getUserDetailsFromFactory : function(){
return user;
}
};
})
,我使用的值从工厂的其它控制器:
$scope.ipForHttp = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
console.log($scope.ipForHttp); //undefined
$scope.loading = false;
$scope.ClientID = userDetailsFactory.getUserDetailsFromFactory().clientidFromSession;
// $scope.dev={};
$scope.getDevice =function(){
console.log($scope.ipForHttp); //undefined
$scope.loading = true;
$http({
method : "GET",
url : $scope.ipForHttp+"getDeviceDetailsReport"
}).then(function mySucces(response) {
OP,有解决这个任务的一种更好的方式 - 用服务和承诺( [$ q](https://docs.angularjs.org/api/ng/service/$q)。你应该看看文档和例子,并试图找出自己。提示 - 具有多重依赖项的代码应移至服务器。如果您需要任何帮助 - 只是评论,我会展示指导您正确的解决方案。 –
这是应该去“其他控制器”的代码,我会给代码添加注释以便于您理解 –
当我使用'console.log()'时,'newValue'是空的。它是'{}'。我在'indeController'(控制器中设置了工厂的值)上设置了一个'timeout'。以便它模拟我上面提到的问题,只有当我主持时才会发生。当我删除'超时'时,我得到所有的值。 – Abhi