8

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?

3
  • 1
    are you sure you don't have two ng-controller="ProductController" in your page? Can you post the HTML? Commented May 16, 2013 at 13:21
  • @sh0ber Yes I am sure. When I search for ng-controller="ProductController" I get only one result.. Commented May 16, 2013 at 14:05
  • When I set up your functions in a fiddle with my HTML, everything works as expected, so I think somehow you are getting two instances of the controller. Maybe that happens elsewhere in your code if not your HTML Commented May 16, 2013 at 14:08

1 Answer 1

30

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..

Sign up to request clarification or add additional context in comments.

2 Comments

doh, i had this problem
This helped me too, thank you. Hint: always be careful when declaring event handlers on object that may have multiple instances running at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.