在 AngularJS 中使用“范围"从另一个控制器调用控制器的方法 [英] Call a method of a controller from another controller using 'scope' in AngularJS

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

问题描述

我正在尝试使用 scope 变量在第一个控制器中调用第二个控制器的方法.这是我的第一个控制器中的一个方法:

I am trying to call a method of second controller in first controller by using scope variable. This is a method in my first controller:

$scope.initRestId = function(){
        var catapp = document.getElementById('SecondApp');
        var catscope = angular.element(catapp).scope();
        catscope.rest_id = $scope.user.username;
        catscope.getMainCategories();
    }; 

我可以设置 rest_id 的值,但由于某种原因我无法调用 getMainCategories.控制台显示此错误:

I am able to set the value of rest_id but I cannot call getMainCategories for some reason. The console shows this error:

TypeError: Object # has no method 'getMainCategories'

TypeError: Object # has no method 'getMainCategories'

有没有办法调用上面的方法?

Is there a way to call the above method?

我使用以下方法同时加载两个应用程序;

I used the following approach to load two apps at the same time;

angular.bootstrap(document.getElementById('firstAppID'), ['firstApp']);
angular.bootstrap(document.getElementById('secondAppID'), ['secondApp']);

我绝对可以在这里使用服务,但我想知道是否还有其他选择可以做到这一点!

I could definitely use a service here, but I wanted to know if there are any other options to do the same!

推荐答案

在两个控制器之间进行通信的最佳方法是使用事件.

The best approach for you to communicate between the two controllers is to use events.

范围文档

在此检查$on$broadcast$emit.

在一般用例中,angular.element(catapp).scope() 的使用是为在 angular 控制器之外使用而设计的,例如在 jquery 事件中.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

理想情况下,您将在控制器 1 中编写一个事件:

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

在第二个控制器中,你只需要做

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

意识到这是两个模块之间的通信

您可以尝试将 firstApp 模块作为对 secondApp 的依赖,在其中声明 angular.module.这样您就可以与其他应用进行通信.

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

这篇关于在 AngularJS 中使用“范围"从另一个控制器调用控制器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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