在Angular.js中实现状态机以控制路由

时间:2012-11-22 04:56:53

标签: angularjs state-machine

任何人都可以帮我集成状态机来控制路由吗?

最好的方法是什么?创建服务?

我需要基本上拦截每个$ location请求,运行状态机并让它弄清楚下一个$ location.path应该是什么。

将问题想象成随着时间推移而添加和删除的一系列问题。用户偶尔访问一次,将用户的答案对象传递给状态机,状态机会指出要加载的问题。这是我的伪代码,但我需要弄清楚在哪里放置这个或我可以挂钩的事件以确保所有路由请求都通过机器。我需要特定的stateMachine控制器吗?我是否创建了服务?我在哪里使用该服务?我是否需要覆盖$ 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;

});

由于

2 个答案:

答案 0 :(得分:7)

你有没看过这个项目?

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

我只是开始试用它,但它看起来应该满足你的需求。

答案 1 :(得分:2)

如何使用ng-click和ng-include而不是拦截$ location更改?使用ng-click调用状态机逻辑,并让它更新一个model / scope属性,指定通过ng-include加载哪个模板:

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

控制器:

$scope.runStateMachine() {
    ... process $scope.answers and set $scope.partialToInclude  ...
}
相关问题