AngularJs如何使用一个控制器方法,变量在其他控制器 [英] AngularJs How can I use one controller methods, variables in other controller
本文介绍了AngularJs如何使用一个控制器方法,变量在其他控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个控制器像下面。我想用一个控制器方法/其他控制器的变量
app.controller(createController,[$范围
功能($范围内)
{
$ scope.i = 0;
$ scope.changeEstimateStatus =功能()
{
的console.log('changeEstimateStatus');
};
}]);
app.controller(editController,[$范围
功能($范围内)
{
//这里我如何可以访问createController的'我'变量
}]);
解决方案
使用共享服务:
app.service(mySharedService,[功能(){
VAR _x = NULL; 返回{
setX的:功能(VAL){_x = VAL},
的getX:函数(){返回_x}
}
}]);
然后注入到你的控制器:
app.controller(createController,[$范围,mySharedService功能($范围,mySharedService){ $ scope.i = mySharedService.getX(); //得到
mySharedService.setX(3); //组
}]);
I have two controllers like below. I want to use first controller methods/variables in other controller
app.controller("createController", ["$scope",
function ($scope)
{
$scope.i = 0;
$scope.changeEstimateStatus = function()
{
console.log('changeEstimateStatus');
};
}]);
app.controller("editController", ["$scope",
function ($scope)
{
//here how can I access 'i' variable of createController
}]);
解决方案
Use a shared service:
app.service("mySharedService", [function() {
var _x = null;
return {
setX: function(val) { _x = val },
getX: function() { return _x }
}
}]);
Then inject into your controller:
app.controller("createController", ["$scope","mySharedService", function($scope, mySharedService) {
$scope.i = mySharedService.getX(); //get
mySharedService.setX(3); //set
}]);
这篇关于AngularJs如何使用一个控制器方法,变量在其他控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文