Wednesday, December 11, 2013

Angularjs we place the same controller, 2 times in the page and chk the output ntg will happen:

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-app="sampleApp">
 
    <div ng-controller="ControllerA">
      <ul>
        <li ng-repeat="item in menu">{{item}}</li>
      </ul>
      <input type="text" ng-model="newItem" /><input type="submit" ng-click="addItem()" />
    </div>

    <div ng-controller="ControllerA">
      <ul>
        <li ng-repeat="item in menu">{{item}}</li>
      </ul>
    </div>
 
  </body>
</html>

app.js:

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;
   });
 }]);

No comments:

Post a Comment