Angular. js Two ways to pass parameters across controller

  • 2021-07-22 08:35:06
  • OfStack

Preface

Since scope is not shared between controllers, if you want to pass parameters between controllers, you may need to do so in other ways. Here are two methods I use to pass parameters between controllers at present.

Note: Refer to article Sharing Data Between Angular Controllers

1. service

You can write 1 service containing get/set, take parameters/assign parameters


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

You can then assign a value in controllerOne and take a value in controllerTwo


//  Assignment 
.controller('one',function(paramService){
 paramService.setResult('one');
})

//  Value 
.controller('two',function(paramService){
 var param = paramService.getResult();
})

2. $stateParams

The second method is used to transfer parameters between routes, which is also widely used and has many use scenarios


//  Reference transmission 
.state('one',{
 url:'one',
 controller:'one',
 template:'one.html',
 params:{
 name:'john'
 }
})

//  Take parameters 
.controller('one',function($stateParams){
 var name = $stateParams.name;
})

others/localStorage

Other methods can use some tips of h5, such as using localStorage to store/take parameters. Other methods are not expected to be used for the time being, and need to be supplemented later.

Ok, the above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or use Angular. If you have any questions, you can leave a message for communication.


Related articles: