Search code examples
angularjsangularjs-controller

define a controller and use twice


I want to user a controller for two separated div and when I do that , it send $http requests twice How can i use the scope of other controllers? here is my code :

            <div data-ng-controller="productCTRL">
                <span ng-model="basket | count"></span>
              ....Some HTML Code......
            </div>
            <div data-ng-controller="AuthController">
                   ....Some HTML Code...
            </div>
            <div data-ng-controller="productCTRL">
               <ul ng-repeat="product in products">
                  <li>{{product.title}}</li>
               </ul>
            </div>

Solution

  • It looks like you want to access the scope of other controllers-

    Three are ways to communicate-

    1. Parent child inherited scope - You have to create a parent controller and child controller can communicate using Parent scope. It is recommended only for tightly coupled controllers.

    2. Event bus - Subscribe can listen on event ($on) and publisher can publish using $emit (current to parent scope can access using $on) or $brodcast (current to child scope can access using $on). Sibling controller can't share the data using this approach. To share the data between sibling controller, you can use $rootScope.broadcast and this event will be listen by all scope including sibling controllers. It is also coupled using event.

    3. Using service - Both controller can share the data using common service because services are singleton.