Friday, May 31, 2013

javascript - AngularJS multiple uses of Controller and rootScope - Stack Overflow

javascript - AngularJS multiple uses of Controller and rootScope - Stack Overflow


I would suggest to use a service that holds the menu and its methods. The service will then broadcast changes to the controller(s).
See a working plunker here: http://plnkr.co/edit/Bzjruq
This is the sample JavaScript code:
angular
 .module( 'sampleApp', [] )
 .service( 'MenuService', [ '$rootScope', function( $rootScope ) {
   return {
      menu: [ 'item 1' ],
      add: function( item ) {
        this.menu.push( item );
        $rootScope.$broadcast( 'MenuService.update', this.menu );
      } 
   };
 }])
 .controller( 'ControllerA', [ 'MenuService', '$scope', function( MenuService, $scope ) {
   $scope.menu = MenuService.menu;

   $scope.addItem = function() {
    MenuService.add( $scope.newItem );  
   };

   $scope.$on( 'MenuService.update', function( event, menu ) {
     $scope.menu = menu;
   });
 }]);
And the sample Html page:



   lang="en">
     charset="utf-8">
    </span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; background-color: transparent;">Custom Plunker</span><span class="tag" style="margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; background-color: transparent; color: rgb(128, 0, 0);">
    
    
  

   ng-app="sampleApp">

    
ng-controller="ControllerA">
  • ng-repeat="item in menu">{{item}}
  • type="text" ng-model="newItem" /> type="submit" ng-click="addItem()" />
    ng-controller="ControllerA">

    • ng-repeat="item in menu">{{item}}



    • share|improve this answer

      No comments: