angularjs - 在 AngularJS 中使用 'scope' 从另一个 Controller 调用一个 Controller 的方法

标签 angularjs angularjs-directive angularjs-scope

我尝试使用 scope 变量在第一个 Controller 中调用第二个 Controller 的方法。这是我的第一个 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。控制台显示此错误:

TypeError: Object # has no method 'getMainCategories'

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

编辑:

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

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

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

最佳答案

在两个 Controller 之间进行通信的最佳方法是使用事件。

Scope Documentation

在此查看 $on$broadcast$emit

在一般用例中,angular.element(catapp).scope() 的使用被设计为在 Angular Controller 外部使用,例如在 jquery 事件内。

理想情况下,您可以在 Controller 1 中将事件编写为:

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

在第二个 Controller 中你只需这样做

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

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

您可以尝试将 firstApp 模块作为您声明 angular.modulesecondApp 的依赖项包含进来吗?这样您就可以与其他应用程序进行通信。

关于angularjs - 在 AngularJS 中使用 'scope' 从另一个 Controller 调用一个 Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468334/

相关文章:

angularjs - 使用 MarkerCluster 和 Angular-Leaflet-Directive 捕获集群上的点击事件

AngularJS - 在 Controller 中访问 ng-if'd 表单

angularjs - 如何为 ngInclude 设置父范围

javascript - 为什么 AngularJS ng-repeat 过滤搜索词不起作用?

angularjs - 在 AngularJS 中有条件应用属性的最佳方法是什么?

javascript - 如何从其他 Controller 调用$http.post?

javascript - Angular 在循环内设置 ng-modal 值

javascript - 以我的 Angular 隐藏特定页面的标题

javascript - 从服务器获取脚本位置

javascript - AngularJS 中的数字没有变化