我尝试使用 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 之间进行通信的最佳方法是使用事件。
在此查看 $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.module
的 secondApp
的依赖项包含进来吗?这样您就可以与其他应用程序进行通信。
关于angularjs - 在 AngularJS 中使用 'scope' 从另一个 Controller 调用一个 Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468334/