$ window.location.href不在AngularJS中工作

Var*_*air 8 html login window.location angularjs

我正在构建一个基本的AngularJS登录页面,$ window.location.href没有将页面重定向到我的系统中由WAMP托管的新html.我甚至尝试将它重新指向谷歌.什么都没发生.我在这里尝试了所有可用的解决方案,似乎没有任何效果.有解决方案吗

JS后跟HTML

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';


  $scope.submit = function() {
    if ($scope.username && $scope.password) {
      var user = $scope.username;
      var pass = $scope.password;
      if (pass == "admin" && user == "admin@admin.com") {
        alert("Login Successful");
        $window.location.href = "http://google.com"; //Re-direction to some page
      } else if (user != "admin@admin.com") {
        alert("Invalid username");
      } else if (pass != "admin" && user == "admin@admin.com") {
        alert("Invalid password");
      }
    } else {
      alert("Invalid Login");
    }
  }


});
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="login.js"></script>
  <link rel="stylesheet" href="login.css">
</head>

<body ng-controller="MainCtrl">
  <form>
    <label>Username:</label>
    <input type="email" ng-model="username" class="lab1" />
    </br>
    </br>
    <label></label>Password:</label>
    <input type="password" ng-model="password" class="lab2">
    </br>
    <button type="submit" ng-click="submit()" class="buttonclass">login</button>
  </form>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

Ale*_*dre 4

在 Angular JS 中,您可以使用$location. 将其注入您的控制器中:

app.controller('MainCtrl', function($scope, $location) { ... }
Run Code Online (Sandbox Code Playgroud)

如果你想重定向到谷歌使用它的url()方法:

$location.url('http://google.fr');
Run Code Online (Sandbox Code Playgroud)

您还可以使用path()相对 url 的方法:

$location.path('home'); // will redirect you to 'yourDomain.xx/home'
Run Code Online (Sandbox Code Playgroud)

https://docs.angularjs.org/api/ng/service/ $location

  • 错误的。你不必“必须使用”;您可以使用。并不因为 $location 是一项服务就强制使用它。根据情况,使用 window.location 没有问题。 (2认同)