javascriptangularjsurl-routingangularjs-routingangularjs-forms

login page redirect in angular validatioon


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

app.config(['$routeProvider', function($routeProvider) {       
  $routeProvider.
  when('/success', {
    templateUrl: 'success.html',
    controller: 'sucCtrl'


  }).
  otherwise({
    redirectTo: '/index'
  })
}])


app.controller('validateCtrl', function($scope, $http, $location) {

  $scope.submit = function(user,password) {
    //for local storage validation

    $http.get('credentials.json').then(function(response) {
      $scope.credentials = response.data;

      if((user === $scope.credentials.username) && (password === $scope.credentials.password)){
        alert("ok");
         $location.path('/success');
      }

      else{
        alert("nit "); }



    });    


  };

})

app.controller('sucCtrl',['$scope', function($scope) {
  alert("succs");

}]);

This might be well a beginner question. I am trying to validate my login form and redirect to success.html on success. But I am unable to navigate to next page. I tried using $location.path('/success'). here is the working sample in plunker.. http://plnkr.co/edit/0v7njznHdtwgpaG2NfwA?p=preview


Solution

  • You missed to write ng-view directive to get route changes to displayed on the view. Also you are messed up with the structuring of your page html. Refer below comments that will help you to make it working and improve it.

    You should put that ng-view directive in body so that all the view will get loaded on basis of route changes.

    Also you should load your form html from the route only, I'd suggest you to add one more route to your config that will say on /login show the form.html(login form)

    Config

    app.config(['$routeProvider', function($routeProvider) {       
      $routeProvider.
      when('/success', {
        templateUrl: 'success.html',
        controller: 'sucCtrl'
      })
      .when('/login', {
        templateUrl: 'form.html',
        controller: 'validateCtrl'
      }).
      otherwise({
        redirectTo: '/login'
      })
    }])
    

    Markup

    <body>
      <div ng-view></div>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.js"></script>
      <script src="login.controller.js"></script>
    </body>
    

    Your success.html should be partial, it shouldn't have the script references again to it they have been loaded from the index page only

    success.html

    <div>
      Success Message
    </div>
    

    Working Demo