English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Two methods of parameter passing between controllers in Angular.js

Introduction

Since controllers do not share scope, if you want to pass parameters between controllers, you may need to implement it in other ways. Here are two methods I currently use to pass parameters between controllers.

Note: Refer to the articleSharing Data Between Angular Controllers

1. Service

You can write a service that includes get/Set the service, retrieve parameters/Assign parameters

.factory('paramService', function(){
 return {
 result: [],
 getResult: function(){
 return this.result;
 ,
 setResult: function(res){
 this.result = res;
 }
 ;
)

Then you can assign values in controllerOne and retrieve them in controllerTwo

// Assignment
.controller('one',function(paramService){
 paramService.setResult('one');
)
// Value acquisition
.controller('two',function(paramService){
 var param = paramService.getResult();
)

Second, $stateParams

The second method is used for parameter transmission between routes and has a wide range of applications and many usage scenarios

// Parameter transmission
.state('one',{
 url:'one',
 controller:'one',
 template:'one.html',
 params:{
 name:'john'
 }
)
// Parameter acquisition
.controller('one',function($stateParams){
 var name = $stateParams.name;
)

others/localStorage

Other methods can use some h5Tips, such as using localStorage to store parameters/Parameter acquisition, other methods have not been thought of or used, and are waiting to be supplemented later.

That's all for this article. I hope the content of this article can bring some help to everyone's learning or using Angular. If you have any questions, you can leave a message for communication.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You may also like