如何从 AngularJS 中的另一个控制器调用函数? [英] How to call a function from another controller in AngularJS?

查看:15
本文介绍了如何从 AngularJS 中的另一个控制器调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 AngularJS 的另一个控制器中调用一个函数.我该怎么做?

I need to call a function in another controller in AngularJS. How can I do this?

代码:

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 中的另一个控制器调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆