![](/img/trans.png)
[英]Angularjs how to call a function of a controller from another controller
[英]How to call a function in a controller from a different controller AngularJS
我正在研究如何强制一个控制器从另一个控制器刷新。
为此,我正在使用一个简单的测试功能:
function test() { alert('test'); }
我认为使用事件是解决此问题的最佳解决方案。
我使用以下代码:
第一控制人
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$emit('testevent'); })
第二控制器
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$on('refreshr', function (event) {
alert('test');
}); })
但这是行不通的! 有什么建议吗?
您可以使用$ rootScope。$ broadcast函数将事件广播到所有子范围。 然后在您的控制器中执行$ scope。$ on。 但是,请确保事件名称相同。
应该是这样。
第一控制人
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$rootScope.$broadcast('testevent');
})
第二控制器
.controller('secondcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$on('testevent', function (event) {
alert('test');
});
})
您的event names
不同,也会在rootScope
级别上广播。
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$rootScope.$broadcast('testevent');
})
.controller('secondcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$on('testevent', function (event) {
alert('test');
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.