[英]How to call a function in a controller from a different controller AngularJS
I'm looking on how to force a controller to refresh from another controller. 我正在研究如何强制一个控制器从另一个控制器刷新。
for that I'm using a simple test function : 为此,我正在使用一个简单的测试功能:
function test() { alert('test'); }
I think using events is the best solution for this issue. 我认为使用事件是解决此问题的最佳解决方案。
I used the following code : 我使用以下代码:
First controller 第一控制人
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$emit('testevent'); })
Second controller 第二控制器
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$on('refreshr', function (event) {
alert('test');
}); })
but this is not working ! 但这是行不通的! any advice ? 有什么建议吗?
You can use $rootScope.$broadcast function to broadcast event to all child scopes. 您可以使用$ rootScope。$ broadcast函数将事件广播到所有子范围。 And then in you controller you do $scope.$on. 然后在您的控制器中执行$ scope。$ on。 But make sure that name of events are the same. 但是,请确保事件名称相同。
This should be it. 应该是这样。
First controller 第一控制人
.controller('firstcontroller', function($rootScope,$scope, $http,$timeout) {
$rootScope.$broadcast('testevent');
})
Second controller 第二控制器
.controller('secondcontroller', function($rootScope,$scope, $http,$timeout) {
$scope.$on('testevent', function (event) {
alert('test');
});
})
You event names
are different, also broadcast on rootScope
level. 您的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.