Atul Verma
Atul Verma

Reputation: 401

Share data between two div using same controller

I have two div's with same controller, both div have almost same data to display. both div's have a button which updates an object. But when one div's button update the object it does not reflect on second div.

<body ng-app="myapp">
  <div ng-controller="ctrl1">
    {{list.greet}}
    <button ng-click="add('hi')">add</button>
  </div>
  <div ng-controller="ctrl1">
    {{list.greet}}
    <button ng-click="add1('hello')">add</button>
  </div>
</body>

Script

var app=angular.module('myapp',[])
.controller('ctrl1',function($scope){
  $scope.list={
    greet:'hola'
  }
  $scope.add=function(data){
    $scope.list.greet=data
  }
   $scope.add1=function(data){
    $scope.list.greet=data
  }
})

Upvotes: 3

Views: 3667

Answers (3)

dting
dting

Reputation: 39307

You can use a service to share data between controllers and different instances of the same controller:

var app = angular.module('myapp', [])
  .controller('ctrl1', function($scope, myService) {
    $scope.a = myService.list;
    $scope.add = function(data) {
      $scope.a.greet.push(data);
    }
  })
  .service('myService', function() {
    this.list = {greet: []};
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<body ng-app="myapp">
  <div ng-controller="ctrl1">
    Ctrl1: <br>
    {{a.greet}}
    <button ng-click="add('c1a')">add</button>
  </div>
  <div ng-controller="ctrl1">
    Ctrl1: <br>
    {{a.greet}}
    <button ng-click="add('c1b')">add</button>
  </div>
</body>

Upvotes: 5

Suvrajyoti Chatterjee
Suvrajyoti Chatterjee

Reputation: 107

Since you have two different ng-controller directives, each div will have its own scope.

The easiest option would be to use the $rootScope.

var app=angular.module('myapp',[])
.controller('ctrl1',['$scope', '$rootScope', function($scope, $rootScope){
  $rootScope.list={
    greet:'hola'
  }
  $scope.add=function(data){
    $rootScope.list.greet=data
  }
   $scope.add1=function(data){
    $rootScope.list.greet=data
  }
}]);

Upvotes: 0

Will Smith
Will Smith

Reputation: 1935

Both the divs have an ng-controller attribute. This means each div has its own instance of the controller. Try adding the ng-controller to a common parent element

<body ng-app="myapp" ng-controller="ctrl1">
  <div>
    {{list.greet}}
    <button ng-click="add('hi')">add</button>
  </div>
  <div>
    {{list.greet}}
    <button ng-click="add1('hello')">add</button>
  </div>
</body>

Upvotes: 5

Related Questions