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

(编辑:jimmy 日期: 2025/9/27 浏览:2)

前言

由于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能带来一定的帮助,如果有疑问大家可以留言交流。

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。