Alex McCabe
Alex McCabe

Reputation: 1892

Two controllers, one scope variable in Angular

Okay so I have two controllers that control two distinctly different parts of the site, that are on the same page.

The first is for a newsletter signup form, the second is for a basket. The second is not directly placed in the DOM as an ng-controller directive, but instead as a controller for a custom directive.

Some code:

<div ng-controller="newsletter-signup">
    <div ng-show="showLoader">
        ... Cool loading animation here ...
    </div>

    ... Form in here ...
</div>

<div basket>
    <div ng-show="showLoader">
        ... Cool loading animation here ...
    </div>

    ... Basket data in here ...
</div>

The problem that I am having is that both of these contain a div that I only want to show under certain conditions, and this div is stored in a template file:

<div ng-show="showLoader">
    ... Cool loading animation here ...
</div>

This however get's shown on both the newsletter and basket when $scope.showLoader is true in either of the controllers.

I can't seem to figure out how to isolate the scopes from each other, but continue to use the same variable name.

The basket directive looks like this:

return {
    link : linkFn,
    scope: '=',
    restrict : 'A',
    controller : 'BasketController'
};

BasketController is never defined in the template.

How can I get to a resolution with this?

I don't want the div for the newsletter to show when the basket is being updated, and likewise, I don't want the div for the basket to show when the newsletter is being updated.

EDIT: We are using the following to define components, I am wondering if this is the root cause.

window.angular.module('Basket', []);
window.angular.module('App', ['Basket']);

Upvotes: 2

Views: 374

Answers (1)

Sten Muchow
Sten Muchow

Reputation: 6701

As posted by @jme11 you need to pass the scope key an object in order to get an isolated scope.

In both places the variable is different, the first place it's defined hence can be true or false. However the second place with the isolated scope unless we directly pass it the variable it will remained undefined and that is a falsy value in JS, hence the ng-show will not pass.

Here is a pen to illustrate the problem better...

return {
    link : linkFn,
    scope: {
      showLoader: '='
    },
    restrict : 'A',
    controller : 'BasketController'
};

http://codepen.io/stenmuchow/pen/BNrLZm?editors=101

Upvotes: 1

Related Questions