AngularJS:使用同一控制器将数据从一个视图传递到另一个视图 [英] AngularJS : Pass data from one view to another with in same controller

查看:122
本文介绍了AngularJS:使用同一控制器将数据从一个视图传递到另一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要:

我在查看表单( 第一 ),并在ajax调用提交成功后,将用户重定向到视图( second ) 。该应用程序只有一个控制器(对于所有视图, )。在这里,用户可以从视图( 第一 )输入表单中的字段,该字段应显示在视图( )和再次在视图中有一个表单( second ),用户可以在表单中输入应显示在视图中的字段( 第三 )。

I have a form in view(first) of my angular application and on success response from the ajax call on submit it redirects the user to the view(second). There is only one controller for the application(for all view). Here, user can enter the fields in the form from the view(first) which should get displayed on the view(second) & again there is a form in the view(second) where user can enter the fields in the form which should get displayed on the view(third).

与所有视图一样(第一,第二,第三个)共享相同的控制器功能。我创建了一个服务 set & 获取从一个视图到另一个视图的数据,并在整个应用程序中使用此服务将数据从一个视图发送到另一个视图视图共享同一控制器。

As all the views(first,second,third) sharing the same controller function.I created one service to set & get the data from one view to another and use this service across the application to send the data from one view to another view sharing the same controller.

问题陈述:

我无法当我从整个应用程序的同一服务获取数据时,将每个表单数据存储在单独的变量中。

I am not able to store each form data in a separate variable as i am getting the data from the same service across the whole application.

关系图:

恶习是有角度的单身人士。因此,当您转到另一个页面时,将不会重新创建它们。因此,当我从控制器中调用 dataService.setData()方法时,它将删除先前存储在服务并进行了更新,这给我带来了问题。我想单独存储所有视图数据,而不要相互覆盖。

As services are singletons in angular. So they won't be recreated when you go to another page.So, when i call a dataService.setData() method from the controller it removes the previous stored data in the service and updated with new one which creates a problem for me. I want to store all views data separately instead of override with each other.

推荐答案

在您的控制器中,创建一些用于每个的不同视图,可以说:

In you controller create some keys for each different view, lets say:

this.keys = {
    "firstView": "firstView",
    "secondView": "secondView",
    "thirdView": "thirdView",
}

,当您调用 setData 方法时,接收到 data 密钥,可以说

and when you call the setData method, receive the data to be stored and the key, lets say

dataService.setData(data, keys.firstView)

并更新您的 getData ,因此您可以选择您想要获得的数据

and update your getData so you can choose which data you want to get like this

dataService.getData(keys.firstView)

现在,您的dataService必须是这样的:

Now your dataService must be like this:

angular.module('app').service('dataService', function() {
    var s = {};
    function setData(data, key){
        s[key] = data;
    }

    function getData(key){
        return s[key];
    }
})

这篇关于AngularJS:使用同一控制器将数据从一个视图传递到另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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