arush_try.com
arush_try.com

Reputation: 440

Implementing a State Machine in Angular.js to control routing

Can anyone help me with integrating a state machine to control routing?

What's the best method to do this? Create a service?

I need to basically intercept every $location request, run the state machine and let it figure out what the next $location.path should be.

Think of the problem like a bank of questions that get added and removed over time. The user visits once in a while, passes in the user's answers object to the statemachine, and the statemachine figures out which question to load. This is my pseudocode, but i need to figure out where to put this or what event I can hook into to make sure all route requests are passed through the machine. Do I need a specific stateMachine controller? Do I create a service? Where do I use the service? Do I need to override $locationProvider?

$scope.user.answers = [{

id: 32,
answer: "whatever"

},
{

id:33,
answer: "another answer"

}]

$scope.questions = [{

id:32, 
question:"what is your name?", 
path:"/question/1"

},{

id:34, 
question:"how old are you?", 
path:"/question/2"

}]

var questions = $scope.questions;

angular.forEach(questions, function(question) {

if(question.id !exist in $scope.user.answers.id) {

$location.path = question.path
break;

});

Thanks

Upvotes: 2

Views: 5564

Answers (2)

Jeff Whelpley
Jeff Whelpley

Reputation: 579

Have you looked into this project yet?

https://github.com/angular-ui/ui-router

I am only starting to try it out, but it looks like it should meet your needs.

Upvotes: 7

Mark Rajcok
Mark Rajcok

Reputation: 364697

Instead of intercepting $location changes, how about using ng-click and ng-include? Use ng-click to call your state machine logic, and have it update a model/scope property that specifies which template to load via ng-include:

<a ng-click="runStateMachine()">process answers</a>
<div ng-include src="partialToInclude"></div>

Controller:

$scope.runStateMachine() {
    ... process $scope.answers and set $scope.partialToInclude  ...
}

Upvotes: 2

Related Questions