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

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

问题描述

我需要在另一个控制器中调用函数的角度js.How是可能的方式请帮助我提前感谢

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 + $

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

因此,在你的情况下,你想在ControllerTwo里面调用ControllerOne的方法,正确的方法是这是:

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天全站免登陆