Angularjs 调用控制器函数后无法更改位置
我已经阅读并尝试应用我能找到的所有方法,但没有一种有效 我只想在用户登录后加载不同的视图:Angularjs 调用控制器函数后无法更改位置,angularjs,angularjs-routing,Angularjs,Angularjs Routing,我已经阅读并尝试应用我能找到的所有方法,但没有一种有效 我只想在用户登录后加载不同的视图: myApp.controller('LoginCtrl', ['$scope', '$rootScope', '$location', function($scope, $rootScope, $location) { $scope.Login = function () { $location.path('/view1'); // $scope.$apply()
myApp.controller('LoginCtrl', ['$scope', '$rootScope', '$location', function($scope, $rootScope, $location) {
$scope.Login = function () {
$location.path('/view1');
// $scope.$apply(); <- error when trying this
};
}]);
索引文件:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Foxy Flakes of Steel</title>
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/app.css" />
</head>
<body>
<div class="container">
<div class="row" ng-view></div>
</div>
<script src="assets/plugins/jquery/jquery-2.0.3.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/plugins/angularjs/angular.min.js"></script>
<script src="assets/plugins/angularjs/angular-route.js"></script>
<script src="assets/js/app.js"></script>
<script src="assets/js/services.js"></script>
<script src="assets/js/controllers.js"></script>
<script src="assets/js/filters.js"></script>
<script src="assets/js/directives.js"></script>
</body>
</html>
模糊的钢片
下面是login.html视图:
<form class="col-md-5 col-md-offset-3">
<div class="rounded-gray">
<div class="row" style="padding: 30px;">
<div class="input-group" style="margin-bottom: 10px;">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="username" class="form-control" ng-model="username">
</div>
<div class="input-group" style="margin-bottom: 10px;">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="text" placeholder="password" class="form-control" ng-model="password">
</div>
<div class="row">
<a href="#" class="btn btn-primary pull-right" style="margin-right: 15px;" ng-click="Login();">Login</a>
</div>
</div>
</div>
</form>
您的登录链接应该是一个按钮。href正在覆盖您的ng单击操作
<button type='button' class='btn btn-primary pull-right' ng-click='Login()'>
Login
</button>
登录
此外,在ng click中不需要分号
(顺便说一句,内联样式非常糟糕)您可以在视图中使用ng href=“#/view1”
,而不是通过ng单击从控制器调用登录方法。我发现的两个技巧
1.
2.
3. 你的路由配置是什么?@Andrey-谢谢,我已经用路由信息更新了我的帖子,还有index.html。。。index.html内容已添加:-)@schomoopy对不起,您还可以演示如何将$socpe.Login绑定到视图中吗?我想它在views/login.html中。你在这两方面都是正确的,但这并不能回答正在发生的事情,登录链接被点击了。当你的答案和我的答案结合在一起时,@schmoopy就会得到一个完整的解决方案。 app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) { $rootScope.$on('$routeChangeStart', function () { if (!Auth.isLoggedIn()) { $location.path('/login'); } else { $location.path('/home'); } }); }]);