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
}
})
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With