本文介绍了$ window.location.href在AngularJS中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

JS后跟HTML

I'm building a basic AngularJS Login page and the $window.location.href did not re-direct the page to a new html in my system, hosted by WAMP. I even tried re-directing it to google. Nothing happens. I tried all the available solutions here and nothing seems to work. Any solutions ?

JS followed by 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 == "[email protected]") {
        alert("Login Successful");
        $window.location.href = "http://google.com"; //Re-direction to some page
      } else if (user != "[email protected]") {
        alert("Invalid username");
      } else if (pass != "admin" && user == "[email protected]") {
        alert("Invalid password");
      }
    } else {
      alert("Invalid Login");
    }
  }


});
<!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>

推荐答案

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

In angular js you can use $location. Inject it in your controller :

app.controller('MainCtrl', function($scope, $location) { ... }

如果要重定向到Google,请使用其url()方法:

And if you want to redirect to google use its url() method :

$location.url('http://google.fr');

您还可以对相对网址使用path()方法:

you can also use path() method for relative url :

$location.path('home'); // will redirect you to 'yourDomain.xx/home'

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

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

这篇关于$ window.location.href在AngularJS中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:17