gpt4 book ai didi

angularjs - 如何从 AngularJS 中的另一个 Controller 调用函数?

转载 作者:行者123 更新时间:2023-12-02 21:33:02 25 4
gpt4 key购买 nike

我需要在 AngularJS 的另一个 Controller 中调用函数。我怎样才能做到这一点?

代码:

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
}
}
]);

最佳答案

Controller 之间的通信是通过 $emit + $on/$broadcast + $on 方法完成的。

因此,在您的情况下,您想在 Controller “二”内调用 Controller “一”的方法,正确的方法是:

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时,您可以发送任何数据作为第二个参数。

关于angularjs - 如何从 AngularJS 中的另一个 Controller 调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com