本文介绍了$on 和 $broadcast 的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有不同视图的 footerController 和 codeScannerController.

I have a footerController and codeScannerController with different views.

angular.module('myApp').controller('footerController', ["$scope", function($scope) {}]);

angular.module('myApp').controller('codeScannerController', ["$scope", function($scope) {
console.log("start");
$scope.startScanner = function(){...

当我点击 footer.html 中的

  • 时,我应该在 codeScannerController 中得到这个事件.

    When I click on a <li> in footer.html I should get this event in codeScannerController.

    <li class="button" ng-click="startScanner()">3</li>
    

    我认为可以用 $on$broadcast 来实现,但我不知道怎么做,也找不到任何地方的例子.

    I think it can be realised with $on and $broadcast, but I don't know how and can't find examples anywhere.

    推荐答案

    如果你想$broadcast使用$rootScope:

    $scope.startScanner = function() {
    
        $rootScope.$broadcast('scanner-started');
    }
    

    然后使用控制器的 $scope 接收:

    And then to receive, use the $scope of your controller:

    $scope.$on('scanner-started', function(event, args) {
    
        // do what you want to do
    });
    

    如果你愿意,你可以在 $broadcast 时传递参数:

    If you want you can pass arguments when you $broadcast:

    $rootScope.$broadcast('scanner-started', { any: {} });
    

    然后接收它们:

    $scope.$on('scanner-started', function(event, args) {
    
        var anyThing = args.any;
        // do what you want to do
    });
    

    范围文档中的文档.

    这篇关于$on 和 $broadcast 的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 09-27 09:10