Search code examples
javascriptangularjsurl-routing

Routing not working in Angular.js


I have an angular.js controller (loginErrorCtrl) that is supposed to redirect to a view (/menu) when the data supplied from an input is equal to a specified string defined in the app (Data.serverToken).

function loginErrorCtrl($scope, Data, $location) {
  $scope.data = Data;
  $scope.validateToken = function(token) {  
    if (token != null) {
      if (token.length == 4) {
        if (token == Data.serverToken) {
          $location.path('/menu');
          } else {
          //error
          return "Invalid Token please try again";
        }
      }
    }
  };
}

The problem is that, when I type the correct token into the input box the $location.path('/menu') doesn't redirect until I hit the backspace. How can I get it to redirect upon successful validation of token?

Code listing on plunker : Angular JS routing


Solution

  • The correct answer was to put the $scope.$apply() as Mark suggested in the comments like so:

    function loginErrorCtrl($scope, Data, $location) {
    $scope.data = Data;
    $scope.validateToken = function(token) {  
    if (token != null) {
      if (token.length == 4) {
        if (token == Data.serverToken) {
          $location.path('/menu');
          $scope.$apply()
          } else {
          //error
          return "Invalid Token please try again";
        }
      }
    }
    };
    }
    

    corrected code