本文介绍了如何从angularjs中的另一个控制器调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在angular js中调用另一个控制器中的函数.请帮助我提前谢谢
I need to call function in another controller in angular js.How it is possible way please help me thanks in advance
代码:
app.controller('One', ['$scope',
function($scope) {
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope',
function($scope) {
$scope.childmethod = function() {
// Here i want to call parentmethod of One controller
}
}
]);
推荐答案
控制器之间的通信通过 $emit
+ $on
/$broadcast
+ $on
方法.
Communication between controllers is done though $emit
+ $on
/ $broadcast
+ $on
methods.
因此,在您的情况下,您想在控制器二"中调用控制器一"的方法,正确的方法是:
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
在调用 $rootScope.$emit
时,您可以发送任何数据作为第二个参数.
While $rootScope.$emit
is called, you can send any data as second parameter.
这篇关于如何从angularjs中的另一个控制器调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!