Share data between two divs using the same controller
I have two divs with one controller, both divs have almost the same data to display. both divs have a button that updates the object. But when one div button updates the object, it doesn't reflect on the 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
}
})
+3
source to share
3 answers
You can use a service to exchange 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>
+5
source to share
Both divs have an attribute ng-controller
. This means that each div has its own controller instance. Try adding ng controller to common parent
<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>
+5
source to share
Since you have two different ng-controller directives, each div will have its own scope.
The easiest option is to use $ 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
}
}]);
0
source to share