What's the correct way to communicate between controllers in AngularJS?

前端 未结 19 2487
猫巷女王i
猫巷女王i 2020-11-21 22:02

What\'s the correct way to communicate between controllers?

I\'m currently using a horrible fudge involving window:

function StockSubgro         


        
19条回答
  •  青春惊慌失措
    2020-11-21 23:06

    You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.

    First we call a function from one controller.

    var myApp = angular.module('sample', []);
    myApp.controller('firstCtrl', function($scope) {
        $scope.sum = function() {
            $scope.$emit('sumTwoNumber', [1, 2]);
        };
    });
    myApp.controller('secondCtrl', function($scope) {
        $scope.$on('sumTwoNumber', function(e, data) {
            var sum = 0;
            for (var a = 0; a < data.length; a++) {
                sum = sum + data[a];
            }
            console.log('event working', sum);
    
        });
    });
    

    You can also use $rootScope in place of $scope. Use your controller accordingly.

提交回复
热议问题