Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
})
like image 587
Atul Verma Avatar asked Dec 05 '25 04:12

Atul Verma


2 Answers

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>
like image 83
dting Avatar answered Dec 07 '25 20:12

dting


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>
like image 32
Will Smith Avatar answered Dec 07 '25 18:12

Will Smith