2016-03-29 59 views
4

我是新來的角js和試圖與ng-viewngRoute指令。如何從角度js控制器中更改視圖?

我有一個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。有人可以告訴我該怎麼做嗎?

謝謝。

回答

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=""; 
} 
+1

謝謝,它的工作!我忘了將$ location添加到控制器參數中 – Minions

1

使用$location.path

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

而且,你已經錯過了在控制器扶養列表中添加$location

function($scope, $http, $location) 
0
if(response.status == "true") 
    $location.path("/home"); 
相關問題