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

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

问题描述

我试图用范围变量来调用第一个控制器第二个控制器的方法。这是一种方法,我的第一个控制器:

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:

类型错误:对象#没有方法'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.

范围文档

在此检查 $关于 $广播 $发出

在一般使用情况下使用 angular.element(catapp).scope()是专为使用的角度控制器之外,像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();
});

和第二控制器你只是做

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