当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular.js跨controller实现参数传递的两种方法

Angular.js跨controller实现参数传递的两种方法

2018年05月01日  | 移动技术网IT编程  | 我要评论

蒲熙来,云杉网络,鲁嚓阁

前言

由于controllers之间不共享scope,如果希望在controllers之间传递参数,可能需要通过其他的方式实现,以下是当前我用到的两种在controllers之间传递参数的方法。

注:参考文章sharing data between angular controllers

一、service

可以写一个包含get/set的service,取参数/赋参数

.factory('paramservice',function(){
 return {
 result:[],
 getresult:function(){
 return this.result;
 },
 setresult:function(res){
 this.result = res;
 }
 };
})

然后可以在controllerone中赋值,在controllertwo中取值

// 赋值
.controller('one',function(paramservice){
 paramservice.setresult('one');
})

// 取值
.controller('two',function(paramservice){
 var param = paramservice.getresult();
})

二、$stateparams

第二种方法用于路由间传递参数,用途也比较广泛,使用场景比较多

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

// 取参
.controller('one',function($stateparams){
 var name = $stateparams.name;
})

others/localstorage

其他方法可以使用一些h5的小技巧,比如使用localstorage来存参/取参,其他的方法,暂时没想到也没用到,有待后续补充.

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用angular能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网