[英]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.