我正在尝试执行登录身份验证,我正在尝试使用angularJS显示进度视图,例如:
app.config(function($locationProvider,$routeProvider) {
$routeProvider
.when('/', {
template: " ",
controller : IndexController
})
.when('/main', {
templateUrl : 'views/main.html',
controller : MainController
})
.when('/login', {
templateUrl : 'views/login.html',
controller : LoginController
})
.when('/progress', {
templateUrl : 'views/progress.html',
controller : ProgressController
})
});
var logged_in = false;
function IndexController($scope,$location){
if(logged_in){
$location.path("/main");
}else{
$location.path("/login");
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function LoginController($scope,$location){
$scope.username = "";
$scope.password = "";
$scope.login = function(){
if($scope.username!="" && $scope.password!=""){
if(!validateEmail($scope.username)){
alert("Invalid e-mail!");
}else{
$location.path("/progress");
setTimeout(function(){ // JUST FOR TEST BEFORE ADD AJAX CONTROL
logged_in = true;
$location.path("/main"); // DOES NOT CALL MainController AND DOES NOT CHANGE TEMPLATE
},2000);
}
}else{
alert("Username & Password obbligatori!");
}
};
$scope.register = function(){
};
}
function ProgressController($scope){
$scope.loading = true;
}
function MainController($scope){}
其中progress.html包含
<div ng-show="loading" class='loading'>
<img src='img/loading.gif'>
</div>
答案 0 :(得分:9)
我认为你应该使用$timeout
http://code.angularjs.org/1.2.13/docs/api/ng。$超时
$timeout(function(){
logged_in = true;
$location.path("/main");
},2000);
当然,它需要在控制器中注入$ timeout。
答案 1 :(得分:4)
如果问题仅出现在以“setTimeout”开头的块上,那是因为$ location.path发生在Angular范围之外。使用内置的$timeout服务而不是setTimeout或将代码包装在$ scope中。$ apply:
$timeout(function() {
$location.path("/main")
}, 2000);
或者,如果您的ajax控制器来自Angular范围之外
$scope.$apply(function() {
$location.path("/main");
});