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

标签 angularjs controller angularjs-scope

我需要在 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/

相关文章:

angularjs - 如何在ng-grid中渲染html格式的内容?

javascript - 如果输入字段为空,则隐藏带 Angular div

java - MVC View 和 Controller 通信的实现。 ( java )

ruby-on-rails - 在 ruby​​ 中使用用户名和密码的 http 请求

angularjs - 从另一个服务调用 AngularJs Controller 方法

javascript - AngularJS 使用范围变量设置 ng-controller

c# - 如何从 C# 类生成 angularjs 模型

angularjs - 观看 iScroll 的 Angular 指令

ruby-on-rails - Ruby on Rails : get route using controller, 操作和参数

javascript - 具有自定义属性的angularjs自定义指令