我已经检查了这个问题的一些主题,我了解控制器是否有启动范围,我需要使用服务,但我不知道如何。
所以这就是问题所在。我有索引页面,其中只有一个div,在div中我有ng-include监听一个名为viewFile()的函数,该函数在controllerA上有描述。在第一次初始尝试时,我加载一个名为login.html的视图并显示它。当用户登录并成功(在controllerB中处理)时,我返回一个令牌,现在我想使用controllerA中的viewFile()加载main.html页面。是否有回叫功能或通知控制器或其他东西?或者我可以为我编写一份服务吗?
我没有使用ngRoute,因为我不希望我的网址更改为mysite.com/#/login.html然后更改为mysite.com /#/ main.html
.controlle("A", function ($scope, sharedVariable){
$scope.token = sharedVariable.getToken();
$scope.viewFile = function(){
if($scope.token == "")
return "view/Login.html";
else
return "view/main.html";
}
}
.controller("B", function ($scope, $http, sharedVariable)){
http({
get ...
.success: function(data){
$scope.token = sharedVariable.setToken();
// INVOKE viewFile from above controller
}
})
}
这里是index.html正文部分
<body>
<div ng-controller="A"><ng-include src="viewFile()"></ng-include></div>
</body>
答案 0 :(得分:1)
看看这个简单的例子http://jsfiddle.net/derkoe/T85rg/presentation/这里personService.person在两个控制器之间共享,类似地你可以在一个服务中编写你的viewFile函数,比如personService。然后从任何控制器调用personService.viewFile。你可以通过$ scope作为其论证。像下面的东西
var myModule = angular.module('myModule', []);
myModule.factory('myService', function($rootScope) {
var sharedService = {};
sharedService.viewFile = function($scope) {
if($scope.token == "")
return "view/Login.html";
else
return "view/main.html";
};
return sharedService;
});
答案 1 :(得分:0)
如果要使用不同的条件更改视图,请在某些服务中定义viewFile函数或将其放在routescope中。然后你可以从多个控制器调用它。但我不认为没有刷新angularjs将能够加载不同的视图html