1

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

5
  • 1
    Try adding $scope.$apply() after setting the path. I didn't download your code, but it sounds like you might be calling validateToken() outside of Angular. A keypress will trigger a digest cycle. Commented Mar 9, 2013 at 22:26
  • @MarkRajcok It still doesn't work. I get an error that says: TypeError: Object #<Object> has no method 'apply' at Object.$scope.validateToken Commented Mar 9, 2013 at 22:31
  • True, scope doesn't have an apply method, but it does have an $apply method -- you probably missed the $. Commented Mar 9, 2013 at 22:34
  • @MarkRajcok Thank you for the help. I did leave out the $ but here is the weird part. In chrome, i get the error: Error: $digest already in progress at Error (<anonymous>) at g until the page crashes whereas in firefox, after a slight delay, it succesfully redirects. Your mention on $digest has also sent me on a path on enlightenment i'm checking out this post Notes On AngularJS Scope Life-Cycle. If you could, please download the snippet it's just 36kb.. thanks! Commented Mar 9, 2013 at 22:51
  • 3
    don't place code in downloads... will never be looked at. Place it in question itself or put a demo together in jsfiddle.net or plnkr.co Commented Mar 9, 2013 at 23:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.