简体   繁体   English

以角度将数据从一个视图传递到另一个视图

[英]Passing data from one view to another in angular

I am trying to load a view with custom message in it. 我正在尝试加载包含自定义消息的视图。 So here is the scenario 所以这是场景

Let say I am on index and I am going to navigate to index2.html. 假设我在索引上,我将导航到index2.html。

Index2.html will render the custom message passed to it. Index2.html将呈现传递给它的自定义消息。 One way is definitely to do it with $routeParams but I don't what to pass the information through the url, rather I want it in a general POST format where passed data is not exposed in url 一种方法肯定是使用$ routeParams来完成的,但是我不希望通过url传递信息,而是我希望采用通用的POST格式,其中传递的数据不会在url中公开

Also I don't want to use localstorage, session or cookie. 我也不想使用localstorage,会话或cookie。 I want it in a way where I pass the data to the view and it should get rendered. 我想要以一种方式将数据传递给视图,并且应该将其呈现。

If anyone can help me with this 如果有人可以帮助我

FACTORY - The right way to share data between pages is a factory/service. 工厂 -在页面之间共享数据的正确方法是工厂/服务。

In this example I'll show you how to share data between two controllers, But it's the same thing. 在此示例中,我将向您展示如何在两个控制器之间共享数据,但这是同一回事。 Once you invoke the service you have access to his instance and his data. 调用服务后,便可以访问其实例和数据。

 var myApp = angular.module('myApp', []); myApp.factory('shareService', function(){ return { title: "some title" }; }); myApp.controller('controller1', function($scope, shareService){ var ctrl1 = this; ctrl1.title = shareService.title; }); myApp.controller('controller2', function($scope, shareService){ var ctrl2 = this; ctrl2.title = shareService.title; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="controller1 as ctrl1"> {{ctrl1.title}} </div> <div ng-controller="controller2 as ctrl2"> {{ctrl2.title}} </div> </div> 

Read more about services on AngularJs doc AngularJs doc上阅读有关服务的更多信息



UPDATE UPDATE

A working example for routing and shared data on plunkr plunkr上路由和共享数据的工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM