AngularJS:在同一个控制器中将数据从一个视图传递到另一个视图视图、中将、控制器、数据

2023-09-06 08:38:44 作者:没有故事

总结:

我的 Angular 应用程序的视图(first)中有一个表单,并且在提交时 ajax 调用的成功响应将用户重定向到视图().应用程序只有一个控制器(for all view).在这里,用户可以从视图(first)输入表单中的字段,这些字段应该显示在视图上(second) &视图中有一个表单(second),用户可以在其中输入应该显示在视图上的表单字段(third).

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).

由于所有视图(first,second,third)共享相同的控制器功能.我创建了一个 serviceset & get 将数据从一个视图发送到另一个视图,并在整个应用程序中使用此服务将数据从一个视图发送到共享同一控制器的另一个视图.

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.

推荐答案

在你的控制器中为 每个不同的视图创建一些 keys,让我们说:

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

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

当您调用 setData 方法时,接收要存储的 datakey,让我们说

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];
    }
})