Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Why is my event handled twice?

I have three controllers: main, product, customer. Controller A is part of my 'masterpage'. Controllers B and C are location dependent.

Controller main:

var MainController = function ($scope, $location, $rootScope, ToolbarService) {
    $scope.addClicked = function () {
        ToolbarService.onAddButtonClick();
    };
};

app.controller({ MainController: MainController });

product:

var ProductController = function ($scope) {

    $scope.$on('handleAddButtonClick', function () {
        alert('Add product');
    });
};
app.controller({ ProductController: ProductController });

customer:

var CustomerController = function ($scope) {

    $scope.$on('handleAddButtonClick', function () {
        alert('Add customer');
    });
};
app.controller({ CustomerController: CustomerController});

toolbarService:

app.service({
    ToolbarService: function ($rootScope) {
        return {
            onAddButtonClick: function () {
                $rootScope.$broadcast('handleAddButtonClick');
            }
        };
    }
});

When my location is #/products and the addClicked of main is invoked, I get the alert 'Add product' twice. Does anybody has a clue why this is?

like image 527
Martijn Avatar asked May 16 '13 12:05

Martijn


1 Answers

The problem was that I also had a controller declared in the routes. So I had configured a controller on my html page and one in the routes provider. This caused that everything executed twice..

like image 192
Martijn Avatar answered Sep 21 '22 00:09

Martijn