Angularjs,在路由之间传递范围 [英] Angularjs, passing scope between routes

查看:26
本文介绍了Angularjs,在路由之间传递范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单跨越几页的情况(可能不理想,但就是这样).我希望整个表单都有一个范围,可以在您进行时填写,以便用户在步骤之间来回切换时,很容易记住状态.

I have a situation with a form that stretches over several pages (might not be ideal, but that is how it is). I'd like to have one scope for the entire form that gets filled in as you go along, so that if the user goes back and forth between steps it's easy to remember the state.

所以我需要用非常伪代码来做:

So I need to do, in very-pseudo-code:

  1. 设置 $scope.val = <一些动态数据>
  2. 单击链接并路由到新模板(可能使用相同的控制器).
  3. $scope.val 应仍与上一页上的值相同.
  1. Set $scope.val = <Some dynamic data>
  2. Click a link and be routed to a new template (probably with the same controller).
  3. $scope.val should still be the same value as it was on the last page.

以某种方式为范围持久化数据是否是解决此问题的正确方法,还是有其他方法?您甚至可以创建一个在路由之间具有持久作用域的控制器,当然,除了将其保存在数据库中.

Is somehow persisting data for the scope the right way to go about this, or is there some other way? Can you even create a controller that has a persisted scope between routes, except for saving it in a database of course.

推荐答案

您需要使用服务,因为服务会在您的应用程序的整个生命周期中持续存在.

You need to use a service since a service will persist throughout your app's life.

假设您想保存与用户有关的数据

Lets say you want to save data pertaining to a user

这是您定义服务的方式:

This is how you define the service :

app.factory("user",function(){
        return {};
});

在你的第一个控制器中:

In your first controller:

app.controller( "RegistrationPage1Controller",function($scope,user){
    $scope.user = user;
    // and then set values on the object
    $scope.user.firstname = "John";
    $scope.user.secondname = "Smith";
});

app.controller( "RegistrationSecondPageController",function($scope,user){
        $scope.user = user;
        // and then set values on the object
        $scope.user.address = "1, Mars";

    });

这篇关于Angularjs,在路由之间传递范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆