如何在角度js中更改控制器的视图?

时间:2016-03-29 09:31:14

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

我是角色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。有人可以告诉我该怎么做吗?

谢谢。

3 个答案:

答案 0 :(得分:1)

使用$location.path

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

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

function($scope, $http, $location)

答案 1 :(得分: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="";
}

答案 2 :(得分:0)

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