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

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

问题描述

总结:

我在我的 Angular 应用程序的视图(first)中有一个表单,并且在 ajax 调用的成功响应中提交它会将用户重定向到视图(second).应用程序只有一个控制器(所有视图).在这里,用户可以从视图(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.

图表:

因为服务是 angular 的单例.因此,当您转到另一个页面时,它们不会被重新创建.这给我带来了问题.我想单独存储所有视图数据,而不是相互覆盖.

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 方法时,接收要存储的 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];
    }
})

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

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