V
V
vladislav9972020-10-28 14:38:44
Angular
vladislav997, 2020-10-28 14:38:44

How to correctly pass a variable between controllers in AngularJs via $rootScope.$broadcast?

Tell me how to correctly pass a variable to AngularJs via $rootScope.$broadcast?

I try like this:

.controller('ctrl1', function($scope, $rootScope) {
        // ...
        $scope.funEvent = function(id) {
            $rootScope.$broadcast("results", id);
        };
    })

.controller('ctrl2', function($scope, $rootScope) {
        $rootScope.$on("results", function(event, id) {
            $scope.results = id;
            console.log(id);
        });
    });


The result works, but strange. it turns out on the first click, console.log does not display anything at all, on the second click it displays the correct ID, on the third click it also displays the correct ID, but already 2 times, on the fourth it displays three times, and so on. tell me how to solve this bug
5f9958120b030582707678.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question