-1

I am trying to update the parent controller $scope value into child controller $scope value using broadcasting as expected working, but not updating while trying to update the child $scope value to parent $scope value by emit function. This is my code:

app.controller('FirstCtrl', function($rootScope, $scope) {
  $scope.firstRegister = function() {
    $rootScope.$broadcast('broadcast', $scope.name)
  };


  $scope.$on('emit', function(events, args) {
    $scope.name = args;

  });

});

app.controller('SecondCtrl', function($rootScope, $scope) {
  $scope.$on('broadcast', function(events, args) {
    $scope.name = args;
  });

  $scope.secondRegister = function() {
    $rootScope.$emit('emit', $scope.name)
  };
  
<div ng-controller="FirstCtrl" class="ng-scope">
<input ng-model="name" />
<button ng-click="firstRegister()">Parent</button>

<div ng-controller="SecondCtrl" class="ng-scope">
  <input ng-model="name" />
  <button ng-click="secondRegister()">Child</button>
</div>

</div>

plnkr link : http://plnkr.co/edit/l9qD0ZO4MptnWx6u3U9c?p=preview

Mukesh
  • 7,630
  • 21
  • 105
  • 159
Govinda raj
  • 613
  • 3
  • 16
  • 31
  • why don't you use `service/factory` instead of this event driven approach..? – Pankaj Parkar Dec 07 '15 at 11:59
  • This seems like a convoluted approach. Use services to communicate between controllers. You could also (although not recommended) just set values on the rootscope from controllers - so why use a broadcast pattern? – Shaun Dec 07 '15 at 12:01
  • Only the $scope value has to be exchanged between the parent and child controllers as per my requirement so that i tried using the event approach(broadcast and emit). May I know the issue from my code. – Govinda raj Dec 07 '15 at 12:07
  • You shouldn't use $rootscope in this way - generally 99% of cases is wrong to use $rootscope as a storage / sharing mechanism . It's lazy. Services/Factories are there for that purpose and can be injected into others that require that dependency. – Shaun Dec 07 '15 at 12:46

1 Answers1

0

I'm broadcasting/emitting event in rootscope then catch the same event in rootscope.Here is the working plunkr can see the click on this link

var app = angular.module('plunker', []);


app.controller('FirstCtrl', function($rootScope, $scope) {
  $scope.firstRegister = function() {
    $rootScope.$broadcast('broadcast', $scope.name)
  };


  $rootScope.$on('emit', function(events, args) {
    $scope.name = args;
  });

});

app.controller('SecondCtrl', function($rootScope, $scope) {
  $rootScope.$on('broadcast', function(events, args) {
    $scope.name = args;
  });

  $scope.secondRegister = function($event) {
    $rootScope.$emit('emit', $scope.name)
  } ;
});
ngLover
  • 4,439
  • 3
  • 20
  • 42