【问题标题】:How to change the view from controller in angular js?如何从角度js中的控制器更改视图?
【发布时间】:2016-03-29 09:31:14
【问题描述】:

我是 Angular js 的新手,正在尝试使用 ng-viewngRoute 指令。

我有一个 loginPage.html,其中我有登录按钮的代码,如下所示

<button class="button button-block" ng-click="login()">Log In</button> 

点击按钮后,loginController 中的登录功能将被执行,我的控制器编写如下:

var App = angular.module('App', ['ngRoute']);

App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'loginPage.html',
        controller: 'loginController'
      }).
      when('/home', {
        templateUrl: 'homePage.html',
        controller: 'homeController'
      });
  }]);

App.controller('loginController', ['$scope', '$http', '$location', function($scope, $http) {
    console.log("Hello from login controller");


    $scope.login = function() {
        //console.log($scope.user);
        $http.post('/login', $scope.user).success(function(response) {
            if(response.status == "true")
                //if the response is true i want to go to homepage.html.

            else
                $scope.error="Invalid login! Please try again";
                $scope.user.email="";
                $scope.user.password="";
      });
    };

}]);

如果是response.status==true,那么我想将我的视图更改为/home。有人可以告诉我该怎么做吗?

谢谢。

【问题讨论】:

    标签: javascript angularjs ngroute ng-view angularjs-ng-route


    【解决方案1】:
    if(response.status == "true")
        $location.path("/home");
    

    不要忘记将$location 添加到您的控制器参数中,如下所示:

    ['$scope', '$http', '$location', function($scope, $http, $location)...
    

    另外,将 else 语句括在括号中,否则只有第一行在语句内:

    else {
        $scope.error="Invalid login! Please try again";
        $scope.user.email="";
        $scope.user.password="";
    }
    

    【讨论】:

    • 谢谢,成功了!我忘了将 $location 添加到控制器参数中
    【解决方案2】:

    使用$location.path

    if(response.status == "true") {
        $location.path('/home');
    }
    

    另外,您错过了在控制器依赖列表中添加$location

    function($scope, $http, $location)
    

    【讨论】:

      【解决方案3】:
      if(response.status == "true")
         $location.path("/home");
      

      【讨论】:

        猜你喜欢
        • 2014-01-03
        • 2014-09-10
        • 1970-01-01
        • 2015-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        相关资源
        最近更新 更多